Question

models.py

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

In above code DateField() generates a date selecting widget in admin site where you can select proper date or enter it manually in a textbox. The problems are:

  1. How do I restrict the user to select a Date that comes under year 2000 to 2100.

  2. when user manually types a date in the text-box, it accepts any date that's in format yy-mm-dd. I need validation so non existing date should not be entered.

Was it helpful?

Solution

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 a form field:

from django import forms

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

More details in the docs, linked to above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top