在Django ModelForm中的self.instance [英] self.instance in Django ModelForm

查看:654
本文介绍了在Django ModelForm中的self.instance的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class MyModelForm( 
def __init __(self,* args,** kwargs):
super(MyModelForm,self).__ init __(* args,** kwargs)
如果self.instance:
...


解决方案

在ModelForm中, .instance源自Meta类中指定的模型属性。在这种情况下,您的 self 显然是ModelForm子类的一个实例,self.instance是(并将保存窗体而不会出错)模型类的一个实例你指定了,虽然你没有这样做在你的例子中。



访问 __ init __ 中的self.instance可能不工作调用父级的 __ init __ 之后,可能会这样做。此外,我不建议直接更改实例。如果您有兴趣,请查看 Github 上的BaseModelForm代码。通过实例参数创建新窗体时,也可以指定实例


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

class MyModelForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        if self.instance:
        ...

解决方案

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.

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.

这篇关于在Django ModelForm中的self.instance的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆