Lu Tran
Lu Tran

Reputation: 401

How to tie django error validation to a specific ForeignKey field, not the entire model

class Business(models.Model):
    is_distributor = models.BooleanField()

class Invoice(models.Model):
    from_business = models.ForeignKey(Business)
    to_business = models.ForeignKey(Business)

To be valid, Invoice.from_business.is_distributor must be True. I can do this in clean() but this error would be tie to the entire model, not the specific from_business field.

I also don't think validator can be hook to ForeignKey field.

Upvotes: 0

Views: 1563

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34583

You can easily get to the instance of the foreign key field and validate a property using the clean method:

from django import forms

from your_app.models import Invoice


class InvoiceForm(forms.ModelForm):
    def clean(self):
        cleaned_data = self.cleaned_data()

        business = cleaned_data.get('business')
        if not business.is_distributor:
            self._errors['business'] = self.error_class(
                ['Business must be a distributor.'])
            del cleaned_data['business']

        return cleaned_data

Upvotes: 2

Related Questions