Django:从表单子类中移除字段

2024-05-06 01:48:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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 #??

有办法做到这一点吗?

注意:我没有ModelForm,因此Meta类和exclude不起作用。


Tags: formnicknameusernameformspasswordwidgetlengthmax
3条回答

我发现了,如果有兴趣请评论。

(在Django 1.7.4中) 扩展表单,代码如下:

class MyForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)

        for key, field in self.fields.iteritems():
            self.fields[key].required = False

    class Meta:
        model = MyModel
        exclude = []

    field_1 = forms.CharField(label="field_1_label")
    field_2 = forms.CharField(label="field_2_label", widget=forms.Textarea(attrs={'class': 'width100 h4em'}),)
    field_3 = forms.CharField(label="field_3_label", widget=forms.TextInput(attrs={'class': 'width100'}),)
    field_4 = forms.ModelChoiceField(label='field_4_label', queryset=AnotherModel.objects.all().order_by("order") )

class MyForm_Extended_1(MyForm):
    field_1 = None


class MyForm_Extended_2(MyForm):
    class Meta:
        model = MyModel
        exclude =[
                    'field_1',
                ]

MyForm_Extended_1将field_1设置为None(db中的列更新为空)

MyForm_Extended_2忽略该字段(在保存期间忽略db中的列)

所以,为了我的目的,我使用第二种方法。

您可以通过重写init方法来更改子类中的字段:

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

Django 1.7在提交b16dd1fe019以获得票证#8620时解决了这个问题。在Django 1.7中,可以按照OP的建议在子类中执行nickname = None。从提交中的文档更改:

It's possible to opt-out from a Field inherited from a parent class by shadowing it. While any non-Field value works for this purpose, it's recommended to use None to make it explicit that a field is being nullified.

相关问题 更多 >