简体   繁体   English

Django-模型形式继承

[英]Django - modelform inheritance

On the Django website this sample code is given: 在Django网站上,给出了以下示例代码:

>>> class RestrictedArticleForm(EnhancedArticleForm):
...     class Meta(ArticleForm.Meta):
...         exclude = ('body',)

My understanding of this is that there's a modelform called EnhancedArticleForm (or ArticleForm and EnhancedArticleForm) and that this should exclude the body field from the form when it's rendered. 我对此的理解是,有一个名为EnhancedArticleForm的模型表单(或ArticleForm和EnhancedArticleForm),并且应在呈现表单时将body字段从表单中排除。 My code looks like this: 我的代码如下所示:

class EditUserForm(UserForm):
    class Meta(UserForm.Meta):
        exclude = ('username',)

I don't want the user to be able to change their username obviously. 我不希望用户能够明显更改其用户名。 But with this code in place, all it does is make the username field the last field to be displayed. 但是有了此代码,所有要做的就是使用户名字段成为最后一个要显示的字段。 It doesn't actually exclude it. 它实际上并没有排除它。 Am I missing something obvious? 我是否缺少明显的东西?

Edit: 编辑:

Apparently this is because of a bug in django. 显然这是由于Django中的错误所致。 I'm trying to overwrite init like so but the form doesn't show up. 我试图像这样覆盖init ,但是表单没有显示出来。 I think it's because I maybe did this wrong: 我认为这是因为我可能做错了:

class EditUserForm(UserForm):
    def __init__(self,instance):
        UserForm.__init__(self,instance)
        del self.fields['username']

This is actually a bug in Django: 这实际上是Django中的错误:

http://code.djangoproject.com/ticket/8620 (See the comment in the ticket further down for your situation) http://code.djangoproject.com/ticket/8620 (请参见故障单中的注释,以了解您的情况)

Unfortunately, it looks like it hasn't seen any action in over a year. 不幸的是,似乎一年多来没有采取任何行动。

One way around this is to override the forms __init__ method and simply remove that field from self.fields. 解决此问题的一种方法是重写__init__方法,然后从self.fields中删除该字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM