简体   繁体   中英

django login not redirecting to index

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 functionality which had nothing to do with this.功能。

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',{})

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$',views.IndexView.as_view(),name='index'),
    url(r'login/',views.user_login,name='login'),]


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  

{% 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.

Okay so this is a weird one but I saw it in production for one of my apps and I think it's to do with the browsers' caching. It's been really hard to reproduce reliably but since I put the following fix out (for something actually unrelated) the problem seems to have been fixed.

Try setting cache-control for the response:

response = HttpResponseRedirect(reverse('index'))
response['cache-control'] = 'private, max-age=0, no-cache, no-store'
return response

Please tell me if this works, it's been bugging me that I haven't found out if my fix has actually worked!

To add middleware, as per Django's docs :

middleware.py

class CacheControlMiddleware(SimpleMiddleware):
    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)
        response['cache-control'] = 'private, max-age=0, no-cache, no-store'
        return response

Then in settings.py, add:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'my_app.middeware.CacheControlMiddleware',
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM