开发者

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

开发者 https://www.devze.com 2023-02-10 14:26 出处:网络
models.py class Completion(models.Model): start_date = models.DateField() end_date = models.DateField() batch = models.ForeignKey(Batch)

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消