Igor
Igor

Reputation: 35

How to force one and only one of two fields to be required in Django?

So here is a Django model example:

    from django.db import models
    from django.core.exceptions import ValidationError

    class MyModel(models.Model):
        field1 = models.CharField(null=True)
        field2 = models.CharField(null=True)

        def clean(self):
            if self.field1 and self.field2:
                raise ValidationError(
                    'Please select only field1 OR field2, not both.')

            elif self.field1 is None and self.field2 is None:
                raise ValidationError(
                    'Please select field1 or field2.')

What I want to achieve is to force an admin of my app to choose one and only one field from two which are available. The problem is that my code prevents well against adding a new object with both fields chosen, but it does not prevent against adding a new object with no fields chosen; the second part works only while the admin wants to edit the object without neither field1 nor field2, but it is possible to add it in the first place, which I wish to prevent against. Any ideas on how can I fix this?

Upvotes: 1

Views: 721

Answers (2)

Kannan Kumarasamy
Kannan Kumarasamy

Reputation: 59

Why Same condition in elif too, should it be like this

def clean(self):
    if self.field1 and self.field2:
        raise ValidationError(
            'Please select only field1 OR field2, not both.')
    elif not (self.field1 or self.field2):
        raise ValidationError(
            'Please select field1 or field2.')

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476547

If the person does not fill in the form field, it will see this as an empty string, not None, yo thus should check the truthiness of the items (so it will match if the field is None or the empty string ''):

def clean(self):
    if self.field1 and self.field2:
        raise ValidationError(
            'Please select only field1 OR field2, not both.')
    elif self.field1 and self.field2:
        raise ValidationError(
            'Please select field1 or field2.')

Upvotes: 2

Related Questions