简体   繁体   中英

Django - modelform inheritance

On the Django website this sample code is given:

>>> 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. 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. I'm trying to overwrite init like so but the form doesn't show up. 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:

http://code.djangoproject.com/ticket/8620 (See the comment in the ticket further down for your situation)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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