Django模型表单ErrorperlyConfigured错误

时间:2017-07-26 17:45:21

标签: python django forms class

  

不正确的配置:创建没有'字段的ModelForm'   属性或'排除'属性被禁止;形成   CustomUserChangeForm需要更新。

from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from login1.models import CustomUser


class CustomUserCreationForm(UserCreationForm):
    def __init__(self, *args, **kargs):
        super(CustomUserCreationForm, self).__init__(*args, **kargs)
        del self.fields['username']

    class Meta:
       model = CustomUser
       fields = ("email",)

class CustomUserChangeForm(UserChangeForm):
    def __init__(self, *args, **kargs):
        super(CustomUserChangeForm, self).__init__(*args, **kargs)
        del self.fields['username']

    class Meta:
        model = CustomUser

2 个答案:

答案 0 :(得分:1)

当你创建一个ModelForm时,它希望你指定在模板中显示哪些字段,即当你在html中执行{{form}}时,你会期望某些字段能够正确呈现吗?因此,在这种情况下,您必须指定fields属性。

class CustomUserChangeForm(UserChangeForm):      
    def __init__(self, *args, **kargs):
        super(CustomUserChangeForm, self).__init__(*args, **kargs)       
        del self.fields['username']

    class Meta:
        model = CustomUser
        fields = '__all__' or ['your_field']           

答案 1 :(得分:0)

您需要在CustomUserChangeForm.Meta类中定义应在表单中包含哪些模型字段:

class CustomUserChangeForm(UserChangeForm):
    def __init__(self, *args, **kargs):
        super(CustomUserChangeForm, self).__init__(*args, **kargs)
        del self.fields['username']

    class Meta:
        model = CustomUser
        fields = '__all__'  #<-- add this or name fields you want to include as sequence