从django.forms继承模型

时间:2019-10-25 17:26:35

标签: python django

我通过使用Forms.ModelForm并运行服务器将模型链接到表单。我收到错误"ModelForm has no model class specified"

这是我正在使用的代码

class UserForm(forms.ModelForm):
    password=forms.CharField(widget=forms.PasswordInput())

    class meta:
        Model= User
        fields=('username' , 'email' , 'password')

1 个答案:

答案 0 :(得分:3)

您在Meta类和model属性中犯了一些错误:它是Meta(以大写字母开头)和model(以小写字母开头):

class UserForm(forms.ModelForm):
    password=forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ('username' , 'email' , 'password')

但这还不够。您无法通过设置属性来设置User模型的密码。 Django 哈希密码。您应该使用User.set_password(..) method [Django-doc]。您可以通过覆盖save()方法来做到这一点:

class UserForm(forms.ModelForm):
    password=forms.CharField(widget=forms.PasswordInput())

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data['password'])
        if commit:
            user.save()
        return user

    class Meta:
        model = User
        fields = ('username' , 'email' , 'password')