Reputation: 83
I have two fields in one model, I want only one valid field in the Admin Form. If one field is valid then the other is not possible to insert data or vice versa. But is necessary put data in one of the two fields for save.
That is possible?
Thanks!
Upvotes: 0
Views: 220
Reputation: 99650
If you want this validation to happen on the backend, you would validate in clean
method of the form. something like this:
class MyAdminForm(forms.ModelForm):
def clean(self):
cd = self.cleaned_data
fields = [cd['field1'], cd['field2']]
if all(fields):
raise ValidationError('Please enter one or the other, not both')
if not any(fields): #Means both are left empty
raise ValidationError('Please enter either field1 or field2, but not both')
return cd
Here is the documentation on using forms with django admin
If you want the validation to happen on the frontend, rather than on form submit, you might want to consider using a javascript solution for that. Here is an answer for a javascript solution
Upvotes: 5