Validate against instance in Django ModelForm

February 22, 2011

I have a Django model form, which displays a subset of fields on the object it is defined for.

I want to run some validatation, validating one of the fields on the form against one of the fields not on the form, but on the instance. Here's how you can access the instance the form is based on during validation.

View

Here's the code in the view:

if request.method == 'POST':
    lLicence = Licence()
    lLicence.customer = lCustomer
    form = LicenceForm(request.POST, instance=lLicence)
    if form.is_valid():
        lLicence = form.save(commit=False)
        # update some more fields
        lLicence.save()

We want to validate that the form field max_users doesn't have a value greater than lLicence.customer.max_allowed_users.

Form

Here's the form definition:

class LicenceForm(forms.ModelForm):
  class Meta:
    model = Licence
    fields = ( 'max_supervisors','max_users','start_date','expiry_date')

def clean_max_users(self):
    lRequested = self.cleaned_data['max_users']
    lMaxAllowed = self.instance.customer.max_allowed_users

    if lRequested > lMaxAllowed:
      raise forms.ValidationError("Value exceeds %s, which is the maximum allowed for this customer" % lMaxAllowed)

    return lRequested