35👍
✅
You could add a clean()
method in your form to ensure that the date is not in the past.
import datetime
class MyForm(forms.Form):
date = forms.DateField(...)
def clean_date(self):
date = self.cleaned_data['date']
if date < datetime.date.today():
raise forms.ValidationError("The date cannot be in the past!")
return date
See http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute
10👍
Another useful solution is to tie validation to fields using the validators keyword argument. This is a handy way of keeping your Form code clear and enabling reuse of validation logic. For e.g
def present_or_future_date(value):
if value < datetime.date.today():
raise forms.ValidationError("The date cannot be in the past!")
return value
class MyForm(forms.Form):
date = forms.DateField(...
validators=[present_or_future_date])
- [Django]-How to clear / maintain a django-sentry database?
- [Django]-How to use the request in a ModelForm in Django
- [Django]-Django Installed Apps Location
3👍
Found out MinValueValidator works perfectly for dates as well.
import datetime
from django.core.validators import MinValueValidator
from django.db import models
...
some_date = models.DateField(validators=[MinValueValidator(datetime.date.today)])
- [Django]-Create django super user in a docker container without inputting password
- [Django]-Python 3 list(dictionary.keys()) raises error. What am I doing wrong?
- [Django]-Target WSGI script cannot be loaded as Python module
2👍
If you are using Django 1.2+ and your model will always force this rule, you can also take a look at model validation. The advantage will be that any modelform based on the model will use this validation automatically.
- [Django]-The `.create()` method does not support writable nested fields by default.
- [Django]-How to redo a migration on django 1.8 after using –fake
- [Django]-How to set up Django website with jQuery
Source:stackexchange.com