Django:从Form子类中删除一个字段 [英] Django: Remove a field from a Form subclass

查看:83
本文介绍了Django:从Form子类中删除一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


nickname = forms.CharField(max_length = 100)
username = forms.CharField(max_length = 100)
password = forms.CharField(widget = forms.PasswordInput)


class LoginFormWithoutNickname(LoginForm):
#我不想要这个字段昵称
昵称=无#??

有没有办法实现?



注意:我没有一个 ModelForm ,所以 Meta exclude 不起作用。

解决方案

一个子类覆盖 init 方法:

  class LoginFormWithoutNickname(LoginForm):
def __init __(self,* args,** kwargs):
super(LoginFormWithoutNickname,self).__ init __(* args,** kwargs)
self.fields.pop('nickname')


class LoginForm(forms.Form):
    nickname = forms.CharField(max_length=100)
    username = forms.CharField(max_length=100)
    password = forms.CharField(widget=forms.PasswordInput)


class LoginFormWithoutNickname(LoginForm):
    # i don't want the field nickname here
    nickname = None #??

Is there a way to achieve this?

Note: i don't have a ModelForm, so the Meta class with exclude doesn't work.

解决方案

You can alter the fields in a subclass by overriding the init method:

class LoginFormWithoutNickname(LoginForm):
    def __init__(self, *args, **kwargs):
        super(LoginFormWithoutNickname, self).__init__(*args, **kwargs)
        self.fields.pop('nickname')

这篇关于Django:从Form子类中删除一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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