Я пытаюсь создать LoginView с настраиваемой формой email вместо username. Вот мой код:
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>
В приведенном выше коде я не копировал вставку из ... импорта ... вещей, поскольку уверен, что проблема не в этом.
В этой строке появляется сообщение об ошибке "Ошибка входа".
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