【问题标题】:Redirect to the main page if authenticated如果通过身份验证,则重定向到主页
【发布时间】:2023-01-20 01:47:18
【问题描述】:

我在重定向时遇到了一些问题。

当我已经登录并尝试转到“/accounts/login”时,它仍然会转到此链接,如果我更改 url.py 路径(例如“accounts/logins”),则重定向有效,但如果未通过身份验证它对我说:

UnboundLocalError:赋值前引用的局部变量“上下文”

并且“/accounts/login”仍然可用

视图.py

def loginPage(request):
    if request.user.is_authenticated:
        return redirect("index")
    if request.method == 'POST':
            username = request.POST.get('username')
            password = request.POST.get('password')

            user = authenticate(request, username=username, password=password)

            if user is not None:
                login(request, user)
                return redirect('index')
            else:
                messages.info(request, 'Username OR password is incorrect')
            context = {}

    return render(request, 'registration/login.html', context)

网址.py

urlpatterns = [
    path('login/', views.loginPage, name='loginPage'),
    path('logout/', views.logoutUser, name='logoutUser'),
    path('register/', views.registerPage, name='registerPage'),
]

【问题讨论】:

    标签: django authentication redirect django-rest-framework django-templates


    【解决方案1】:

    为了在登录后重定向到特定的 url,您可以在 settings.py 中设置以下内容:

    LOGIN_REDIRECT_URL = '/'
    

    希望这就是你要找的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-19
      • 2015-12-21
      • 2016-12-30
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      相关资源
      最近更新 更多