Reputation: 7281
Suppose I have a class with two fields and both fields are blank, but i want at least one field to be filled.
class MyClass(models.Model):
url1 = models.URLField(blank=True)
url2 = models.URLField(blank=True)
def clean(self):
if not self.url1 and not self.url2:
raise forms.ValidationError('message here')
return self.url1
I think because I set the two fields to blank=True. Don't know if using clean() here is true or not and also what to return from it.
Nothing showing in {{form.non_field_errors}}
Thanks
Upvotes: 0
Views: 1874
Reputation: 3710
you can use the clean()
method on a form object. Currently you are trying to make data validation not on a Form object but instead on a database model.
Have a look on https://docs.djangoproject.com/en/dev/ref/forms/validation/ to know more about form validation.
from django.db import models
from django import forms
class MyClass(models.Model):
"Your model"
url1 = models.URLField(blank=True)
url2 = models.URLField(blank=True)
class MyClassForm(forms.ModelForm):
"Your form object"
def clean(self):
if not self.cleaned_data['url1'] and not self.cleaned_data['url2']:
raise forms.ValidationError('message here')
return self.cleaned_data
class Meta:
model = MyClass
Upvotes: 2