Django实现用户登录
- 修改urls.py 文件:
from django.conf.urls import url
from django.contrib import admin
from cmdb import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'h.html/', views.home),
url(r'login', views.login),
]
-
创建以下目录:
新建login.html (用户登录表单 ) 代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
label{
width:80px:
text-align: right:
}
</style>
</head>
<body>
<!--/* action="/login/" 指向urls.py 的login,以post方式提交表单 */-->
<from action="/login" method="post">
<p>
<label for="username">用户名: </label>
<input id="username" type="text" />
</p>
<p>
<label for="password">密码: </label>
<input id="password" type="text" />
<input type="submit" value="提交" />
</p>
</from>
</body>
</html>
-
修改views.py 文件:
views.py 代码如下:
from django.shortcuts import render
# Create your views here.
from django.shortcuts import HttpResponse
def login(request):
f = open('templates/login.html', 'r', encoding='utf-8')
date = f.read()
f.close()
return HttpResponse(date)
def home(request):
return HttpResponse('<h1>CMDB</h1>')
-
运行:
-
效果图如下(http://127.0.0.1:8000/login):
再修改以下login.html代码:
<style>
label{
width:80px;
text-align: right;
display:inline-block;
}
</style>
-
再运行效果图:
-
代码再修改-- 修改views.py文件代码(比上述代码减少):
from django.shortcuts import render
# Create your views here.
from django.shortcuts import HttpResponse
from django.shortcuts import render # new
def login(request):
# f = open('templates/login.html', 'r', encoding='utf-8')
# date = f.read()
# f.close()
# return HttpResponse(date)
return render(request,'login.html') # new
def home(request):
return HttpResponse('<h1>CMDB</h1>')
-
再刷新浏览器同样获得同样效果: