4

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')
4
  • 1
    it is model (with a lowercase), not Model. Furthermore it is Meta (with an uppercase), not meta. Commented Oct 25, 2019 at 17:27
  • Note that you will need to use set_password over the standard behavior of the ModelForm to hash the password. Commented Oct 25, 2019 at 17:28
  • Have you tried the fixed that Willem Van Onsem suggested? If so that could be posted as the answer, although that has less to do with an actual programming problem and is simply a syntactic error. Commented Oct 25, 2019 at 17:52
  • @bartcubrich: the typo's yes, but the set_password is an issue as well. Commented Oct 25, 2019 at 18:01

1 Answer 1

3

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')
Sign up to request clarification or add additional context in comments.

3 Comments

I have done hashing of password in my views file. This is shown below python if user_form.is_valid() and profile_form.is_valid(): user=user_form.save() user.set_password(user.password) user.save()
@NishantKumar: this really looks something to do in the form. For example Django's UserCreateForm does this in the form as well. You can then for example use such form in a CreateView, UpdateView, etc. without needing to alter the predefined view logic.
thanks got my error solved actually in Model M should be in lowercase

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.