1๐
โ
You have to define a custom clean method on you model (rather than on your form to make this validation more reusable) :
models.py
from django.core.exceptions import ValidationError
class Person(models.Model):
PARTY_BENEFIT = (
('NO', 'No'),
('YES_DEMOCRAT', 'Yes, Democrat'),
('YES_REPUBLICAN', 'Yes, Republican'),
('YES_OTHER', 'Other')
)
party_benefit = models.CharField(null=True, max_length=100, default=None, choices=PARTY_BENEFIT, verbose_name="Does one or another political party benefit more than the others due to Biased coverage in the media? \n And if so which?")
party_benefit_message = models.CharField(max_length=1000, blank=True, verbose_name='If you selected \"Other\", please specify:')
def clean(self):
if self.party_benefit == 'YES_OTHER' and not self.party_benefit_message:
raise ValidationError({'party_benefit_message': ['You must enter a message.']})
More info on model validation here : https://docs.djangoproject.com/en/1.8/ref/models/instances/#django.db.models.Model.clean
You form does not change.
๐คCharlesthk
0๐
I would write it like this (clean
method inside your ModelForm
):
def clean(self):
benefit_option = self.cleaned_data.get('party_benefit')
message = self.cleaned_data.get('party_benefit_message')
if benefit_option and benefit_option == 'YES_OTHER' and message is None:
raise forms.ValidationError('Message is required when \"Other\" is checked')
๐คbellum
- [Answer]-Django CreateView does not save object
- [Answer]-How to get header and data from Models in Python?
Source:stackexchange.com