Django add extra field to a ModelForm generated from a Model

对着背影说爱祢 提交于 2019-11-28 17:24:16
relekang

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

ZG101

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!