I have got a login screen, which upon successful authentication should show user details on the same base URL , it used to work just fine all these days, and all of a sudden it's throwing 302 response code HTTP POST /login/ 302 [0.60, 127.0.0.1:53864] when the correct username and password is entered, no redirection is initiated, it forever keeps loading.
What's more strange is that when I reload the same tab or open a new tab, it is correctly logged in and shows the appropriate details. No changes related to login functionality were made, the only recent change I made was to add reset password functionality which had nothing to do with this.
user_login
def user_login(request):
field = None
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
try:
field = UserModel.objects.get(user__username=username)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('index'))
else:
messages.error(request,'username or password not correct')
return HttpResponseRedirect('../')
else:
print("Error logging in{}".format(password))
messages.error(request,'Invalid username/password combination')
return HttpResponseRedirect('../')
except Exception:
#return HttpResponse("ACCOUNT NOT ACTIVE!!!")
messages.error(request,'Entered username does not belong to any account')
return HttpResponseRedirect('../')
else:
return render(request,'app/login.html',{})
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$',views.IndexView.as_view(),name='index'),
url(r'login/',views.user_login,name='login'),]
AIM: To show login and user details(logged in view) on the same base URL(127.0.0.1:8000), i.e if a user is logged in, show user details, else show login form
IndexView
class IndexView(TemplateView):
template_name = 'app/index.html'
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
if self.request.user.is_authenticated:
today = date.today()
print(today)
context['products'] =ProductModel.objects.filter(usr=self.request.user)
print("LOGGED IN")
return context
index.html
{% extends 'app/base.html' %}
{%block title %}
<title>TITLE</title>
{% endblock %}
{%block body %}
{% if user.is_authenticated %}
{% include 'app/header.html' %}
<div class="container">
<h1>Welcome {{user.username}}</h1>
{% else %}
<!--LOGIN FORM HERE-->
{% endif %}
{% endblock %}
It was working without any problems all these days, not sure of what's causing this. Please suggest fixes for this problem. Thanks.