def post(self, request: HttpRequest): form = LoginForm(request.POST) if not form.is_valid(): return render( request, "authentication/login.html", { "next": request.POST.get("next", ""), "form": form }, ) username_email = form.cleaned_data["username_email"] password = form.cleaned_data["password"] try: # Try login by email user_by_email = UserModel.objects.get(email=username_email) user = authenticate(username=user_by_email.username, password=password) except ObjectDoesNotExist: # Try login by username user = authenticate(username=username_email, password=password) if user: # Login user login(request, user) # If user didn't check remember_me # session will expire on browser close if not form.cleaned_data.get("remember_me"): request.session.set_expiry(0) # If url has next parameter # and the url is local (starts with '/' ) # redirect user to the next url next_url = request.POST.get("next") if next_url and next_url.startswith("/"): return redirect(next_url) # If next didn't exist or wasn't local # redirect to learning home return redirect("learning:home") form.add_error("", "نام کاربری یا رمز عبور اشتباه است") return render( request, "authentication/login.html", { "next": request.POST.get("next", ""), "form": form }, )
def loginPage(request): form = LoginForm() if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) if updateUserSubscriptionState(user): return redirect('/product/list') else: return redirect('authentication:profile') else: form.add_error('password', 'Inicio de sesión incorrecto') return render(request, 'login.html', {'form': form}) return render(request, 'login.html', {'form': form})
def post(self, request, *args, **kwargs): """ POST method login user (if credentials are valid and user is active) and redirects to main page :param request: POST request :type request: :return: HTTP response :rtype: HttpResponse """ form = LoginForm(request.POST or None) context = {'form': form} if form.is_valid(): cleaned_form = form.cleaned_data user = authenticate(username=cleaned_form['username'], password=cleaned_form['password']) if user is not None and user.is_active: login(request, user) return HttpResponseRedirect('/') else: form.add_error(None, "Wrong credentials") return render(request, self.template_name, context)