self.instance in Django ModelForm

前端 未结 2 761
臣服心动
臣服心动 2021-02-02 10:50

What does self.instance in Django ModelForm constructor mean and where can I find a documentation about it?

class MyModelForm(ModelForm):
    def __init__(self,          


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 11:11

    You can find the documentation on django's website.

    https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-clean-method

    Just search the page for every reference to "instance", and you should find what you need.

    # Load up an instance
    my_poll = Poll.objects.get(id=1)
    
    # Declare a ModelForm with the instance
    my_form = PollForm(request.POST, instance=my_poll)
    
    # save() will return the model_form.instance attr which is the same as the model passed in
    my_form.save() == my_poll == my_form.instance
    

提交回复
热议问题