在开始登陆功能之前,先说下整体流程,首先查看到127.0.0.1:8080/index/,接着去urls.py文件中去配置urlpatterns,再到views.py文件中实现某个动作事件的函数,最后去index.html文件中去修改布局。
以上只是拿登陆流程举例说明,其他功能的流程程也是如此,请举一反三理解
1、登陆页布局实现,index.html文件实现
<html>
<head>
<title>Django Pages</title>
</head>
<body>
<h1>发布会管理</h1>
<form>
<input name="username" type="text" placeholder="username"><br>
<input name="password" type="password" placeholder="password"><br>
<button id="btn" type="submit"></button>
</form>
</body>
</html>
2、请求方式介绍,当客户端通过http协议向服务器提交请求时,最常用到的方法就是GET和POST。
GET:从指定的资源请求数据
POST:向指定的资源提交要被处理的数据
GET请求
使用GET传递参数,只需在form表单中添加属性method=“get”即可post请求
使用post传递参数,只需将上述method的值改为post即可
<form method="post">
3、处理登陆请求,在index.html文件,为form添加action属性
<form method="post" action="/login_action/">
4、到url.py文件中配置该路径
url(r'^login_action', views.login_action),
5、到views.py文件中添加login_action方法
# 登陆方法
def login_action(request):
if request.method == 'POST':
username = request.POST.get('username', '')
password = request.POST.get('password', '')
if username == 'admin' and password == 'admin123':
return HttpResponse('login success!!!')
pass
else:
return render(request, 'index.html', {'error':'username or password error!!!'})
pass
pass
6、截止到第五步之后,可以试下是否能登陆,会发现提示CSRF错误,错误截图如下
解决办法,在index.html 文件中添加{% csrf_token %}
<form method="post" action="/login_action/">
<input name="username" type="text" placeholder="username"><br>
<input name="password" type="password" placeholder="password"><br>
<button id="btn" type="submit">登陆</button>
{% csrf_token %}
</form>
7、打开浏览器,输入http://127.0.0.1:8000/index/,然后输入用户名为admin,密码为admin123,点击登陆,登陆成功截图如下
当前登陆用户名和密码是自己写死的,后续会从表中读取用户名和密码。
自己也可以试试输入错误的用户名和密码,看会得到什么结果。