Reputation: 501
I'm using crispy forms to make my forms look nice and added the following validation:
forms.py
class Meta:
widgets = {
'dob': DatePickerInput(
options={
"format": "MM/DD/YYYY",
"showClose": False,
"showClear": False,
"showTodayButton": False,
}
),
}
def clean(self):
data = self.cleaned_data
born = data.get('dob')
today = date.today()
age = (today.year - born.year - ((today.month, today.day) < (born.month, born.day)))
if age < 14:
msg = ("Sorry, you must be atleast 14 years old")
self.add_error('dob', msg)
if age > 110:
msg = ("You entered a date of birth outside of the accepted range. Please try again.")
self.add_error('dob', msg)
return data
models.py
dob = models.DateTimeField('Date of birth (mm/dd/yyyy)', null=True, default=now)
My problem is that this error message displays at the top of the page as a flash message, while other messages (which i did not set but are built into crispy, such as when a user leaves a required field blank) are displayed as a pop up message box under the field the errors related to.
I am wondering how I can make my added validation error appear the same as other in-built crispy error messages, for consistency.
Image - (https://i.sstatic.net/RkTUT.jpg)
Thank you.
Upvotes: 0
Views: 214
Reputation: 820
If you are overriding clean method then you can use add_error():
def clean(self):
data = self.cleaned_data
age = data.get("age")
if age < 14:
msg = "Sorry, you must be atleast 14 years old to study with IPC IELTS."
self.add_error('age', msg)
if age > 110:
msg = "You entered a date of birth outside of the accepted range. Please try again."
self.add_error('age', msg)
return data
You can also put validation on your Model or on Form:
from django.core.validators import MinValueValidator,MaxValueValidator
from django.utils.translation import ugettext_lazy as _
class YourModel(models.Model):
age = models.DecimalField(..., validators=[
MinValueValidator(14, message=_("Sorry, you must be atleast
14 years old to study with IPC IELTS.")),
MaxValueValidator(110, message=_("You entered a date of birth outside of the
accepted range. Please try again."))
])
So that you don't need to style it manually for that field.
Upvotes: 1