How to restrict a user to choose a date between a range of years in django?

models.py

class Completion(models.Model):
    start_date = models.DateField()
    end_date = models.DateField()
    batch = models.ForeignKey(Batch)
    topic = models.ForeignKey(Topic)

In the above code DateField(), a date picker is created on the administrator’s website, where you can select the appropriate date or enter it manually in the text box. Problems:

  • How can I limit the user to select a date that comes from 2000 to 2100.

  • when a user manually enters a date in a text box, he accepts any date that is in the format yy-mm-dd. I need a check, so you should not enter a non-existing date.

+3
source share
1 answer

Check out validators !

First define your validator:

from django.core.exceptions import ValidationError

def validate_current_century(value):
    if value < 2000 or value > 2100:
        raise ValidationError(u'%s is not a valid year!' % value)

Now you can use it in your model field:

class Completion(models.Model):
    start_date = models.DateField(validators=[validate_current_century])
    end_date = models.DateField(validators=[validate_current_century])

And also in the form field:

from django import forms

class MyForm(forms.Form):
    current_century_field = forms.DateField(validators=[validate_current_century])

More details in the documents related to the above.

+9
source

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


All Articles