Answer the question
In order to leave comments, you need to log in
User authorization using email or login?
Hello Toaster!!!
There is a task to make user authorization via email or login (one field).
This means that there are two fields on the authorization page: Login/Email and password.
You also need to write down the corresponding errors.
My implementation of simple authorization.
views.py
class RegisterFormView(FormView):
form_class = UserCreationForm
print form_class
success_url = "/info/login/"
template_name = "register.html"
def form_valid(self, form):
form.save()
return super(RegisterFormView, self).form_valid(form)
class LoginFormView(FormView):
form_class = AuthenticationForm
template_name = "login.html"
success_url = '/info/'
def form_valid(self, form):
self.user = form.get_user()
login(self.request, self.user)
return super(LoginFormView, self).form_valid(form)
class LogoutView(View):
def get(self, request):
logout(request)
return HttpResponseRedirect("/info/")
url(r'^login/$',views.LoginFormView.as_view(),name='login')
url(r'^logout/$', views.LogoutView.as_view(), name='logout')
<!DOCTYPE html>
<html>
<head>
<title>Авторизация</title>
</head>
<body>
<form action="{%url 'login' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">LOGIN</button>
</form>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
I did this authorization by login (aka email) or phone. I say right away that I don’t use the form, because there are only two fields. The Person model (linked to User OneToOneField) has a phone field.
class Login(TemplateView):
template_name = 'core/home.html'
def post(self, request, *args, **kwargs):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is None:
try:
possible_user = Person.objects.get(phone=username)
user = auth.authenticate(username=possible_user.user.username, password=password)
except Person.DoesNotExist:
user = None
if user is not None:
if user.is_active:
auth.login(request, user)
return redirect(request.GET.get('next') or request.META.get('HTTP_REFERER') or reverse('home'))
else:
messages.add_message(request, messages.ERROR, 'Пользователь не активен')
else:
messages.add_message(request, messages.ERROR, 'Пользователь не найден')
return redirect(reverse('home'))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question