Hi I am very new at Django. I am working on a small project in which i am using modelform. For date field i want to do custom validation i.e. whenever a user enter a date before today's date it should display a error message near date field. I have written code as per the django's documentation, but it gives ValidationErrors for the raise statement in modelform. like ValidationError at /add_task/ [u"Please enter valid date. Either today's date or after that."]
Please help me how to overcome this problem. Thanks in advance.
Codes of my models:
from django.db import models
class MyTask(models.Model):
summary=models.CharField(max_length=100)
description=models.CharField(max_length=500)
due_date=models.DateField(null=True)
completed_status=models.BooleanField()
def __unicode__(self):
return self.summary
Codes of my modelform:
from django.forms import ModelForm, Textarea
from django.forms.extras.widgets import SelectDateWidget
from django.core.exceptions import ValidationError
from assignment.models import MyTask
import datetime
class AddTaskForm(ModelForm):
class Meta:
model=MyTask
fields=('summary','description','due_date')
widgets = {
'description': Textarea(attrs={'cols': 50, 'rows': 10}),
'due_date':SelectDateWidget(),
}
def get_due_date(self):
diff=self.cleaned_data['due_date']-datetime.date.today()
if diff.days<0:
raise ValidationError("Please enter valid date. Either today's date or after that.")
else:
return self.cleaned_data['due_date']
def get_summary(self):
return self.cleaned_data['summary']
def get_description(self):
return self.cleaned_data['description']
Django's form (and model) fields support use of utility functions and classes known as validators. A validator is a callable object or function that takes a value and returns nothing if the value is valid or raises a ValidationError if not.
How this works is, if the request method is POST, the form gets initiated with the POST data, then it's validated with the is_valid() call, so the form object now has the validation error messages if it's invalid. If it's valid, it's saved and redirected.
cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).
Your validation method needs to be called clean_due_date
. In Django < 3 it should raise forms.ValidationError
, but in Django 3 it should use core.exceptions.ValidationError
.
I have no idea what the get_summary
and get_description
methods are for, they aren't called and don't do anything useful.
See the Django 3 docs here and the Django 2 docs here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With