Bit68
Bit68

Reputation: 1546

Either/Or fields in Django models

I was building a django model that has two fields, only one of them is required.

class course_data(models.Model):
    link = models.CharField(max_length = 500, null = True, blank = True)
    uploaded_file = models.FileField(upload_to='course_files', null = True, blank = True)
    name = models.CharField(max_length = 200, null = True, blank = True)
    description = models.TextField(null = True, blank = True)    
    applies_to = models.ManyToManyField('course') 

I want the entry to be valid only if the "link" field is provided or if the 'uploaded_file' field is provided or both. I can't make both parameters optional since they can be both left blank. Any suggestions?

Upvotes: 1

Views: 2510

Answers (3)

NerV
NerV

Reputation: 51

you can override clean method:

class course_data(models.Model):
    link = models.CharField(max_length = 500, null = True, blank = True)
    uploaded_file = models.FileField(upload_to='course_files', null = True, blank = True)
    name = models.CharField(max_length = 200, null = True, blank = True)
    description = models.TextField(null = True, blank = True)    
    applies_to = models.ManyToManyField('course')

    def clean(self):
        if self.link == None and self.uploaded_file is None:
            raise ValidationError(_('Fields uploaded_file and link required.'))

Upvotes: 2

Hedde van der Heide
Hedde van der Heide

Reputation: 22439

You can use a ModelForm and override its clean method to get the behaviour you want. If you want to use the admin, you can add the custom behaviour with a ModelAdmin

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599778

This isn't something you'd deal with in the model definition. You would handle it at the form level, by making both fields required=False but checking in the form's clean() method that one of them was supplied.

Upvotes: 4

Related Questions