I am trying to add a restriction so that the user always selects the checkbox to 'True'. It looks like that, but unfortunately it does not work properly. Any help will be appreciated.
models.py
class OrderingMassage(models.Model):
website_rules = models.BooleanField(default=None, blank=True)
forms.py
class OrderingMassageForm(forms.ModelForm):
class Meta:
model = OrderingMassage
fields = ('website_rules')
def clean_website_rules(self):
data = self.cleaned_data['website_rules']
if data == None:
raise forms.ValidationError("please accept the rules of the website")
else:
return data
If something always (should be) true, then you should not use a Model
in the first place. A model stores data. But if all records all have the same, then there is not much data. If a column is always True
, then what is the use to store that column?
A second problem you have is that a BooleanField
[Django-doc] (well the form field) will yield False
as "empty value. So it is probably more Pythonic to check the truthiness, like:
class OrderingMassageForm(forms.Form):
website_rules = forms.BooleanField(label='I accept the rules of the website.')
def clean_website_rules(self):
data = self.cleaned_data['website_rules']
if not data:
raise forms.ValidationError("please accept the rules of the website")
else:
return data
You thus do not need to call .save()
of that form. But .is_valid(..)
will validate the form, and thus can render errors.