Python Django ModelForm 中的 self.instance
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18265023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
self.instance in Django ModelForm
提问by jazzblue
What does self.instance in Django ModelForm constructor mean and where can I find a documentation about it?
Django ModelForm 构造函数中的 self.instance 是什么意思,我在哪里可以找到有关它的文档?
class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
if self.instance:
...
采纳答案by Fiver
In a ModelForm, self.instance is derived from the model
attribute specified in the Meta class. Your self
in this context is obviously an instance of your subclass of ModelForm, and self.instance is (and will be on saving the form without errors) an instance of the model class you specified, although you have not done so in your example.
在 ModelForm 中,self.instance 派生自model
Meta 类中指定的属性。您self
在此上下文中显然是 ModelForm 子类的实例,而 self.instance 是(并且将在保存表单时没有错误)您指定的模型类的实例,尽管您在示例中没有这样做。
Accessing self.instance in __init__
may not work, though doing so after calling the parent's __init__
probably will. Further, I wouldn't recommend trying to change the instance directly. If you are interested, have a look at the BaseModelForm code on Github. The instance
can also be specified when creating a new form via the instance
argument.
访问 self.instance in__init__
可能不起作用,尽管在调用父级__init__
可能的意愿后这样做。此外,我不建议尝试直接更改实例。如果您有兴趣,请查看Github上的 BaseModelForm 代码。在instance
创建通过一种新的形式时,也可以指定instance
参数。
回答by Bryan
You can find the documentation on django's website.
您可以在 django 的网站上找到文档。
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-clean-method
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