仅仅将静态页面返回给用户是不够的,用户和服务器之间还需要互动起来。今天就来写一个提交用户名和密码的页面。
在templates目录下创建input.html文件,输入以下内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户管理</title>
</head>
<body>
<h1>用户输入</h1>
<form action="/input", method="post"> <!--action是html文件名字 -->
{% csrf_token %} <!--django有跨站请求保护机制要求必须添加此行 -->
用户名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
在视图文件mysite/login/views.py中添加input方法:
def input(request):
if request.method == 'POST':
print('This is a post request')
username = request.POST.get('username')
password = request.POST.get('password')
print(username, password)
elif request.method == 'GET':
print('This is a get request')
return render(request,'input.html')
在mysite/mysite/urls.py中添加path
urlpatterns = [
path('admin/', admin.site.urls),
path('index', views.index,name='index'), #给视图添加路由
path('input', views.input,name='input')
运行程序,启动浏览器打开页面http://127.0.0.1:8000/input 显示如下内容
输入用户名和密码后点击提交,在pycharm上打印出输入内容:
System check identified no issues (0 silenced).
You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
January 25, 2019 - 06:08:41
Django version 2.1.5, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
This is a get request
[25/Jan/2019 06:08:44] "GET /input HTTP/1.1" 200 612
This is a post request
admin 123456
[25/Jan/2019 06:08:56] "POST /input HTTP/1.1" 200 612
用chrome抓包查看提交结果: