需求
请求 http://127.0.0.1:8000/student/login/ 登录后显示个人信息
流程
#新建工程 test32
#新建项目 stu
#修改 settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'stu'
]
#修改urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^student/',include('stu.urls'))
]
#修改子路由 stu/urls.py
import views
urlpatterns = [
url(r'^login/$',views.index_login),
url(r'^usercenter/$',views.usercenter)
]
#修改 stu/views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
# Create your views here.
class User(object):
def __init__(self,uname,pwd):
self.uname = uname
self.pwd = pwd
import jsonpickle
def index_login(request):
if request.method == 'GET':
return render(request,'login.html')
else:
#接收请求参数
uname = request.POST.get('uname')
pwd = request.POST.get('pwd')
#判断
if uname == 'zhangsan' and pwd == '123':
user = User(uname,pwd)
# jsonpickle.dumps(user) 将python对象序列化成普通字符串
request.session['login'] = jsonpickle.dumps(user)
return HttpResponseRedirect('/student/usercenter/')
else:
return HttpResponseRedirect('/student/login/')
def usercenter(request):
#获取session 中的数据
user = request.session['login']
# jsonpickle.loads(user) 将普通字符串反序列化成python对象
uuser = jsonpickle.loads(user)
return render(request,'center.html',{'user':uuser})
#新增加 templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/student/login/" method="post">
{% csrf_token %}
<p>姓名:<input type="text" name="uname"/></p>
<p>密码:<input type="password" name="pwd"/></p>
<p><input type="submit" value="login"/></p>
</form>
</body>
</html>
#新增加 templates/center.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>欢迎账号{{ user.uname }}登录成功</h3>
</body>
</html>
#效果