Returning annually to Django returns "Make sure this value is less than or equal to 2016" in 2017

In my database, I have an entry where the field of the year is 2016, but I need to change it to 2017. When I use the Django admin to change it to 2017, I get "Make sure that this value is less than or equal to 2016.". What is wrong with my model?

class Track (models.Model): artist = models.ForeignKey(Artist, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Artist") title = models.CharField(max_length=100, verbose_name="Title") year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[MinValueValidator(1900), MaxValueValidator(datetime.datetime.now().year)], verbose_name="Year") timestamp = models.DateTimeField(default=timezone.now) 
+5
source share
1 answer

This is a classic problem with django models / forms, etc.! The code datetime.datetime.now().year inside the validator is executed only once, when the source file is read for the first time. It is not executed every time a form is submitted! So it mattered 2016 when it was first executed and still has the same meaning.

To quickly see my point, restart the application server - then it will be fine (the model will be reevaluated and will receive 2017 as datetime.date.today (). Year!). Of course, in order to really fix this problem, you must change the validation logic to use a special validator (MaxValueValidator cannot be used), which will run every time your form is submitted.

For instance:

 def my_year_validator(value): if value < 1900 or value > datetime.datetime.now().year: raise ValidationError( _('%(value)s is not a correcrt year!'), params={'value': value}, ) ... # And then in your model: year = models.PositiveSmallIntegerField( null=True, blank=True, validators=[my_year_validator], verbose_name="Year" ) 
+7
source

Source: https://habr.com/ru/post/1262160/


All Articles