day88-django登录校验

1、urls.py

from django.contrib import admin
from django.urls import path
from django.shortcuts import HttpResponse,render,redirect
def login(request):
#第一次请求,浏览器输入127.0.0.1:8000/login,服务器返回登录页面
if request.method == 'GET':
print(request.method) # GET
print(request.GET) # <QueryDict: {}>,如果浏览器输入127.0.0.1:8000/login/?p=123,
# 结果是<QueryDict: {'p': ['123']}>,?p=123是给GET传参。
return render(request, 'login.html')
#第二次请求,接着在登录界面点登录,127.0.0.1:8000/login不变,还是在这个页面,属于POST操作
else:
print(request.method) # POST
print(request.POST) #<QueryDict: {'usn': ['root'], 'psd': ['123123']}> 它是字典
u = request.POST.get('usn')#request.POST['usn']通过索引取值也行,但是当html的name="usn"的usn跟get('usn')的usn不一样时会报错
p = request.POST.get('psd')#如果使用get方法取值,当值不对时会返回None,不报错
if u == 'root' and p == '123123':
# return redirect('http://www.sogo.com') #redirect跳转到指定网址
return render(request,'index.html',{
'user':['tom','marry'],#key是html的特殊字符,而value用于替换它,key就是value
'dict':{'name':'alex','age':18},
'sql_data':[{'id':'1','user':'tom','psd':'111'},{'id':'2','user':'marry','psd':'222'}]
})
else:
return render(request, 'login.html',{'error':'用户名或密码错误'})#返回登录页面并且替换html的特殊字符{{ error }}

urlpatterns = [
path('admin/', admin.site.urls),
path('login/', login)
]

2.login.html
<body>
<form method="POST" action="/login/">
<label>用户名 <input type="text" name="usn"></label>
<label>密码 <input type="password" name="psd"></label>
<input type="submit" value="登录">
{{ error }}
</form>
</body>
3.index.html
<body>
{{ user.0 }}
{{ user.1 }}
{{ dict.name }}
{{ dict.age }}
{% for dict in sql_data %}
{{ dict.id }}
{{ dict.user }}
{{ dict.psd }}
{% endfor %}
<ul>
{% for item in user %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<table border="1">
{% for dict in sql_data %}
<tr>
<td>{{ dict.id }}</td>
<td>{{ dict.user }}</td>
<td>{{ dict.psd }}</td>
<td><a href="">编辑</a> | <a href="">删除</a></td>
</tr>
{% endfor %}
</table>
</body>



原文地址:https://www.cnblogs.com/python-daxiong/p/12623120.html