1

I have a customized User model

class User(AbstractBaseUser):
   email       = _models.EmailField     (max_length=252, unique=True)
   username    = _models.CharField      (max_length=252, blank=True, null=True)
   staff       = _models.BooleanField   (default=False)
   superuser   = _models.BooleanField   (default=False)
   active      = _models.BooleanField   (default=True)

   USERNAME_FIELD = 'email'

This is the form

class UserLoginForm(_f.ModelForm):
    password = _f.CharField(widget=_f.PasswordInput())

    class Meta:
        model = User
        fields = ['email', 'password']

And this is the view

from django.contrib.auth import authenticate, login
from django.views.generic import FormView,
from .forms import UserRegistrationForm, UserLoginForm
class UserLoginView(FormView):
    form_class = UserLoginForm
    success_url = '/'
    template_name = 'accounts/user_login.html'

    def form_valid(self, form):
        email = form.cleaned_data.get('email')
        password = form.cleaned_data.get('password')
        user = authenticate(request=self.request, email=email, password=password)

        if user:
            login(self.request, user)
            return super(UserLoginView, self).form_valid(form)

        return super(UserLoginView, self).form_invalid(form)

the urls.py of the app

from django.urls import path
from .views import UserLoginView, UserRegistrationView
app_name = 'accounts'
urlpatterns = [
    path('login/', UserLoginView.as_view(), name='login'),
    path('register/', UserRegistrationView.as_view(), name='register'),
]

the urls.py of the project

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('applications.accounts.urls', namespace='namespace_accounts')),
]

This the template user_login.html of the view UserLoginView

{% extends 'accounts/login_base.html' %}
{% load staticfiles %}

{% block content %}
<form method="POST">
    <div class="form-group">
        {% csrf_token %}
        {{ form.as_p }}
    </div>
    <button type="submit" class="btn btn-dark">Login</button>
</form>
{% endblock %}

After registrating as new user, the user is redirected to the login page, with the credentials, the login keeps saying "User with this Email already exists."

Note: The email field on the model User is unique.

Is obvious that the login page is trying to make another registration somehow, and this "somehow" is what it's confusing me.

What could I possibly be doing to solve this "User with this Email already exists."?

R.R.C.
  • 5,439
  • 3
  • 14
  • 19

1 Answers1

2

As I suspected, the UserLoginView was trying to make another registration, that is, create a new user again, instead of authenticate and do the login. That was happening because my form inherited from forms.ModelForm; changing from forms.ModelForm to forms.Form solved the problem.

The credit goes to this Answer which punched right at the problem!

R.R.C.
  • 5,439
  • 3
  • 14
  • 19