简体   繁体   English

django 登录未重定向到索引

[英]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.我有一个登录屏幕,成功验证后应该在同一个基本 URL 上显示用户详细信息,它过去一直工作得很好,突然间它抛出 302 响应代码HTTP POST /login/ 302 [0.60, 127.0.0.1:53864]当输入正确的用户名和密码时,不会启动重定向,它永远保持加载。 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网址.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), ie if a user is logged in, show user details, else show login form目的:在相同的基本 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索引.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.确实很难可靠地重现,但是自从我发布了以下修复程序(对于实际上不相关的东西)之后,问题似乎已经解决了。

Try setting cache-control for the response:尝试为响应设置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!请告诉我这是否有效,我一直困扰着我还没有发现我的修复是否真的有效!

To add middleware, as per Django's docs :要添加中间件, 根据 Django 的文档

middleware.py中间件.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:然后在settings.py中添加:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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