I
I
inalan2020-09-12 01:46:57
Django
inalan, 2020-09-12 01:46:57

LoginView with email form instead of username?

I'm trying to create a LoginView with a custom email form instead of username. Here is my code:

urls.py

**********
  urlpatterns = [
    path("login/", views.LoginView.as_view(), name="login"),
    path("logout/", views.log_out, name="logout"),
]


forms.py
class LoginForm(forms.Form):
    email = forms.EmailField(widget=forms.EmailInput(attrs={"placeholder": "Email"}))
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={"placeholder": "Password"})
    )

    def clean(self):
        email = self.cleaned_data.get("email")
        password = self.cleaned_data.get("password")
        try:
            user = models.User.objects.get(email=email)
            if user.check_password(password):
                return self.cleaned_data
            else:
                self.add_error("password", forms.ValidationError("Password is wrong"))
        except models.User.DoesNotExist:
            self.add_error("email", forms.ValidationError("User does not exist"))


views.py
class LoginView(FormView):
    template_name = "users/login.html"
    form_class = forms.LoginForm
    success_url = reverse_lazy("core:home")

    def form_valid(self,form):
        email = form.cleaned_data.get("email")
        password = form.cleaned_data.get("password")
        user = authenticate(username=email,password=password)
        if user is not None:
            login(self.request,user)
            return HttpResponse(request.user.is_authenticated)
        else:
            return HttpResponse("Login failed")
        return super().form_valid(form)


def log_out(request):
    logout(request)
    return redirect(reverse("core:home"))


html file
<form method="POST" action="{% url 'users:login' %}">
    {% csrf_token %}
{{ form.as_p }}
<button>Login</button>
</form>


In the code above, I didn't copy-paste from ... import ... things as I'm pretty sure that's not the problem.

The error message "Login Failed" appears on this line.

if user is not None:
            login(self.request,user)
            return HttpResponse(request.user.is_authenticated)
        else:
            return HttpResponse("Login failed")`


in setting.py I have this
AUTH_USER_MODEL = "users.User"
and my models.py inherits AbstructUser and some additional fields are added

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-09-12
@tumbler

In authenticate you pass email instead of username, so nothing converges.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question