Nishant Kumar
Nishant Kumar

Reputation: 73

Inheriting Models from django.forms

I am linking my models to my forms by using forms.ModelForm and running the server. I get the error "ModelForm has no model class specified"

Here is the code I am using

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

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

Upvotes: 4

Views: 46

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476564

You made some errors in your Meta class and model attribute: it is Meta (starting with an uppercase), and model (starting with a lowercase):

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

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

But that will not be sufficient. You can not set the password of the User model by setting the attribute. Django hashes the password. You should use the User.set_password(..) method [Django-doc]. You can do so by overriding the save() method:

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')

Upvotes: 3

Related Questions