django登录未重定向到索引

问题描述:

我有一个登录屏幕,在成功进行身份验证后,该屏幕应在同一基本URL上显示用户详细信息,过去这些天一直运行良好,突然间,如果正确,则会抛出302响应代码HTTP POST /login/ 302 [0.60, 127.0.0.1:53864]输入用户名和密码,不启动重定向,它永远保持加载状态. 更奇怪的是,当我重新加载相同的选项卡或打开新的选项卡时,它已正确登录并显示适当的详细信息.没有进行任何与登录功能有关的更改,我最近所做的唯一更改是添加了与该功能无关的重置密码功能.

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.

用户登录

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'),]

目标:在同一基本URL(127.0.0.1:8000)上显示登录名和用户详细信息(登录视图),即,如果用户已登录,则显示用户详细信息,否则显示登录表单
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.

好的,这很奇怪,但是我在其中一款应用的生产环境中看到了它,我认为与浏览器的缓存.确实很难可靠地进行复制,但是由于我(对于实际上不相关的内容)进行了以下修复,因此问题似乎已得到解决.

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.

尝试为响应设置cache-control:

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!

要添加中间件,请按照Django文档的说明 :

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

然后在settings.py中添加:

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',
]