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)
您可以在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
归档时间: |
|
查看次数: |
26263 次 |
最近记录: |