本文章示例是创建一个登录的界面,输入用户名和密码,并进行用户验证,点击登录后跳转一个我们指定的页面。
应用中的views.py代码展示:
from django.shortcuts import render
from django.http import HttpResponseRedirect
# Create your views here.
from django.http import HttpResponse
from django.contrib import auth
def index(request):
return render(request,"index.html")
def login_action(request):
if request.method=="POST":
username = request.POST.get("username")
password = request.POST.get("password")
if username =="admin" and password =="admin123":
#验证用户名
user = auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request,user)
response = HttpResponseRedirect("/even_manage")
request.session["user"] = username#把cookies添加到浏览器
return response
def even_manage(request):
username = request.session.get("user" ,"") #获取浏览器的session
return render(request,"even_manage.html" ,{"user":username})
templates/index.html代码展示:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h2>会义签到登录</h2>
<form method ="post" action = "/login_action/">
<input name="username" type="text" placeholder="username" ><br>
<input name="password" type="text" placeholder="username"><br>
<button id="btn" type="submit">登录</button>
</form>
</body>
</html>
templates/even_manage代码展示:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>整天给我出问题</h1>
</body>
</html>
项目urls.py代码展示:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^sign/$', include("sign.urls")),
url(r'^login_action/$', views.login_action),
url(r'^even_manage/$', views.even_manage),
]
应用中urls.py代码式展示:
from django.conf.urls import url
from . import views
urlpatterns=[
url(r"^$",views.index ,name="index"),
url(r"^$",views.login_action ,name="login_action"),
url(r"^$",views.even_manage ,name="even_manage"),
]
效果图,是不是很简陋?
如果想限制网页要登录才能访问只需要在函数的前面加上@login_required,
如果读者不太明白,目录文件名代表什么意思,可以参考一下以前的笔记文章。
网友评论