Answer the question
In order to leave comments, you need to log in
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"),
]
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"))
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"))
<form method="POST" action="{% url 'users:login' %}">
{% csrf_token %}
{{ form.as_p }}
<button>Login</button>
</form>
if user is not None:
login(self.request,user)
return HttpResponse(request.user.is_authenticated)
else:
return HttpResponse("Login failed")`
Answer the question
In order to leave comments, you need to log in
In authenticate you pass email instead of username, so nothing converges.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question