1、
参考地址:https://blog.csdn.net/Pansc2004/article/details/80494793
(1)https://blog.csdn.net/weixin_42134789/article/details/81700922?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.control&dist_request_id=1328592.8898.16147388268452879&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.control
(2)
https://www.cnblogs.com/ellisonzhang/p/11417162.html
清除浏览器缓存,直接访问 http://localhost/event_manage/,发现无需登陆,也可以直接访问该网页。
Django中解决该问题的方法是,给对应的views.py中的方法加上装饰器 @login_required。
step1: 在views.py中加入如下代码
-
from django.shortcuts import render
-
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
-
from django.contrib import auth
-
from django.contrib.auth.decorators import login_required
-
-
-
# Create your views here.
-
-
# def index(request):
-
# return HttpResponse("欢迎!")
-
-
def index(request):
-
return render(request, "index.html")
-
-
-
def login_action(request):
-
# request = HttpRequest(request)
-
username = request.POST.get('username', '')
-
password = request.POST.get('password', '')
-
user = auth.authenticate(username=username, password=password)
-
if user is not None:
-
request.session['user'] = username # 将session信息记录到浏览器
-
request.session['psw'] = password
-
# Correct password, and the user is marked "active"
-
auth.login(request, user)
-
return HttpResponseRedirect('/event_manage/')
-
else:
-
return render(request, 'index.html', {'wronglyInput': '用户名或密码输入错误!'})
-
-
-
def event_manage(request):
-
username = request.session.get('user', '') # 读取cookie
-
password = request.session.get('psw', '')
-
return render(request, "event_manage.html", {'user': username, 'psw': password})
step2: 重新尝试访问 http://localhost/event_manage/ ,已经不能登陆了
step3: 虽然访问被成功限制了,但我们希望是自动跳转到index页面,让用户输入账号和密码。 注意上面的路径,@login_required会将其设置到 /account/login/的路径上去,那么只要我们在urls.py中做相应的路径设置,让其跳转到index页面即可。
-
urlpatterns = [
-
url(r'^$', views.index),
-
url(r'^index/$', views.index),
-
url(r'^admin/', admin.site.urls),
-
url(r'^login_action/', views.login_action),
-
url(r'^event_manage/', views.event_manage),
-
url(r'^accounts/login/$', views.index),
-
]
step4: 再次运行,访问event_manage,跳转成功