Django Form Inheritance

April 3, 2011

You can inherit forms classes when using Django. This example defines a superclass that allows the website field to be edited, whilst the subclass prevents this field being changed. The validation for latitude and longitude is common to both forms.

Note the use of inheritance on the Meta class.

CO_ORD_REGEX = "^\-?[0-9]+\.[0-9]+$"

class EditBandSuperuserForm(ModelForm):
    """
    Form for entering a new band, allows edit of website
    """
    class Meta:
        model = Band
        fields = ('name', 'region','latitude','longitude', 'website', 'contact_email', 'status')

    def clean_latitude(self):
        """
        Validate latitude is in correct format
        """
        lLatitude = self.cleaned_data['latitude']
        lValue = lLatitude.strip()
        if lValue:
            lRegEx = re.compile(CO_ORD_REGEX) 
            if lRegEx.match(lValue) == None:
                raise forms.ValidationError("Please enter the location in decimal notation, for example 50.7687")
            return lLatitude

    def clean_longitude(self):
        """
        Validation longitude is in correct format
        """
        lLongitude = self.cleaned_data['longitude']
        lValue = lLongitude.strip()
        if lValue:
            lRegEx = re.compile(CO_ORD_REGEX) 
            if lRegEx.match(lValue) == None:
                raise forms.ValidationError("Please enter the location in decimal notation, for example -1.9282")
            return lLongitude

class EditBandForm(EditBandSuperuserForm):
    """
    Form for entering a new band, prevents edit of website
    """
    class Meta(EditBandSuperuserForm.Meta):
        exclude = ('website',)