在Django中有没有提到两个登录地址?

2024-09-30 08:23:51 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的应用程序中,如果用户第一次登录,他将被重定向到配置文件页面,从第二次开始,他将被重定向到主页(我的应用程序中的VChome)。 所以我决定用url.py和views.py来写这个

网址.py

from django.urls import path
from . import views

urlpatterns = [
    path('VC/',views.VChome, name='VChome'),
    path('profile/',views.update_profile,name='profile'),
    path('users/login/', views.login_user, name='login'),
    path('login/done/', LoginRedirectView.as_view(), name='login_redirect'),       
]

视图.py

class LoginRedirectView(generic.View):
def get(self, request, *args, **kwargs):
    logout(request)
    username = password = ''
    if request.POST:
        username = request.POST['username']
        password = request.POST['password']
        userLL = CustomUser.objects.get(username=username)
        # print(userLL)
        last_login = userLL.last_login
        # print(last_login)
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                if last_login == None:
                    return HttpResponseRedirect(reverse("profile"))
                else:
                    return HttpResponseRedirect(reverse("VChome"))
    return render(request, 'login.html')

登录.html

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
{% block content %}
  <form method="post">
        <strong><p>Sign in</p></strong>
        <p>Username</p>
        {% csrf_token %}
        <input type="text" id="username" name="username"  placeholder="Username">
        <p>Password</p>
        {% csrf_token %}
        <input type="password" name="password" id="password" placeholder="Password">
        <input type="submit" value="Login">      
  </form>
{% endblock %}
</body>
</html>

我有profile.html和VChome.html模板,我确信它们在views.py中正确呈现

这里的问题是,如果我提到LOGIN\u REDIRECT\u URL='VChome',登录页面将被重定向到VChome

如果我没有提到,登录页面将重定向到/accounts/profile

我希望根据views.py中login\u user中提到的最后一个\u login约束重定向登录页


Tags: pathnamepyifrequesthtmlusernamelogin
1条回答
网友
1楼 · 发布于 2024-09-30 08:23:51

我会保持简单,创建一个视图来执行逻辑并返回重定向到VChome或其他任何地方

views.py

class LoginRedirectView(View):
    def get(self, request, *args, **kwargs):
        if request.user.blahblah:
            return HttpResponseRedirect(reverse('CAhome'))
        else:
            return HttpResponseRedirect(reverse('profile'))

urls.py

    ...
    path('login/done/', LoginRedirectView.as_view(), name='login_redirect'),
    ...

settings.py

LOGIN_REDIRECT_URL = 'login_redirect'

从技术上讲,您可以从同一请求调用不同的视图,从而为用户节省一个HTTP重定向。但是我认为对于这个特定的用例来说,这可能不值得付出努力

相关问题 更多 >

    热门问题