Django: How to use User ModelForm for log in?

I'm trying to use a modelForm for a login rather than a Form (to avoid repetition):

class LoginForm(forms.ModelForm):
    class Meta:
        model = get_user_model()
        widgets = {
            "password": forms.PasswordInput(),
        }
        fields = ("email", "password")

However, since the email field has a unique=True, and since forms can be used to create objects, when running is_valid() method on the form, I get an error: User with this E-mail already exists.

What is the right way to handle this? Thanks.

My guess is that you're using a generic view and so the view is calling the save() method on the LoginForm, and since the LoginForm is a ModelForm it tries to save the user on the database, that's why you have that error.

You could override the save() method on your form and just pass so nothing get's saved

or (even better) you could just use the LoginView from django and set the USERNAME_FIELD on your User model. So you won't need to create your own LoginForm


Back to Top