Django ModelForm中的self.instance

jaz*_*lue 18 python django

Django ModelForm构造函数中的self.instance意味着什么,我在哪里可以找到它的文档?

class MyModelForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        if self.instance:
        ...
Run Code Online (Sandbox Code Playgroud)

Fiv*_*ver 15

在ModelForm中,self.instance是从modelMeta类中指定的属性派生的.您self在此上下文中显然是ModelForm的子类的实例,并且self.instance是(并且将保存表单而没有错误)您指定的模型类的实例,尽管您的示例中没有这样做.

访问self.instance __init__可能不起作用,尽管在调用父代__init__可能会这样做之后这样做.此外,我不建议尝试直接更改实例.如果您有兴趣,请查看Github上的BaseModelForm代码.在instance创建通过一种新的形式时,也可以指定instance参数.


Bry*_*yan 9

您可以在django的网站上找到该文档.

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

只需在页面中搜索"实例"的每个引用,您就应该找到所需的内容.

# 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
Run Code Online (Sandbox Code Playgroud)


小智 5

现在我们需要使用更准确的方式进行检查,因为 self.instance 不能为 None (也许旧的方式检查仍然有效) https://github.com/django/django/blob/65e03a424e82e157b4513cdebb500891f5c78363/django/forms/models。 py#L302

    if self.instance.pk is not None: # or just if self.instance.pk
Run Code Online (Sandbox Code Playgroud)

尝试 print(self.instance, type(self.instance), self.instance.pk) ,可以发现: type is <class...> but self.instance is None