[Django]-Django add extra field to a ModelForm generated from a Model

93👍

You can add a field to a ModelForm. Unless you add a field named temp_id to your model you do not need to change this form when you change you model.

Example (with a model named Point):

class PointForm (forms.ModelForm):
    temp_id = forms.IntegerField()

    class Meta:
        model = Point

    def save(self, commit=True):
        # do something with self.cleaned_data['temp_id']
        return super(PointForm, self).save(commit=commit)

UPDATE: Forgot self in def save() and changed modelname to Point

5👍

To follow up relekang’s answer, I had to be reminded to also return the last line as shown, so that the object’s get_absolute_url() method could be automatically called on submission of the form:

return super(PointForm, self).save(commit=commit)

Leave a comment