从views.py进行身份验证后重定向到特定页面



我有三个Html页面home.Html、destination.Html和login.Html。Home.html只有一个按钮,如果我点击这个按钮,如果用户通过了身份验证,他将被重定向到destination.html,否则将重定向到login.html(我使用的是内置登录功能,工作正常(,当用户登录时,特定的用户名会出现在Home.html页面上,但当我再次点击按钮时,它会再次重定向到login.html.

views.py这是home.html和destination.html的视图部分,我使用内置函数进行身份验证。

from django.contrib import auth
from django.shortcuts import redirect, render
from rest_framework.permissions import IsAuthenticated

def home(request):
if request.method == 'POST':
user = auth.authenticate()
if user is IsAuthenticated:
return render(request, 'destination.html')
else:
return redirect('login/')
else:
return render(request, 'home.html')
def destination(request):
return render(request, 'destination.html')

urls.py

from django.contrib import admin
from django.urls import path
from newapp import views
from django.contrib.auth.views import LoginView
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('destination', views.destination, name= 'destination'),
path('login/', LoginView.as_view(template_name='login.html')),
]

试试这个:

from django.contrib import auth
from django.shortcuts import redirect, render
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
def home(request):
if request.method == 'POST':
user = authenticate()
if user is not None:
login(request, user)
return render(request, 'destination.html')
else:
return redirect('login/')
else:
return render(request, 'home.html')
@login_required
def destination(request):
return render(request, 'destination.html')

在这里,我们检查用户是否为"无",然后启动一个会话,因为在该特定用户登录之前,创建的数据将不可用。不要忘记在settings.py中提到LOGIN_URL="/login/",这将有助于防止用户通过url操作访问destination.html。只有当会话打开时才有可能。

最新更新