在读这篇文章之前,确保你看过:Django创建APP这篇文章。在这里我们呢将实现用户登录页面。
按照前面的介绍需要在django总工程目录下的mdjango中的urls.py添加URL规则:
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', views.login),
]
接着创建我们在myapp文件夹下的views.py中修改代码:
from django.shortcuts import HttpResponse
def login(request):
return HttpResponse('<h1>This is Login!</h1>')
login函数处理的是用户访问http://127.0.0.1:8000/login/页面,返回给用户的内容。通常是一个Form表单,来接受用户的输入,我们呢可以在templates文件夹下创建一个login.html页面,用来展示给用户登录。一般情况下templates文件夹就是存放我们呢的模板文件。有了login.html页面,我们呢就可以在login函数中打开这个页面并返回给用户views.py:
from django.shortcuts import HttpResponse
def login(request):
with open('templates/login.html','r',encoding='utf-8') as f:
data=f.read()
return HttpResponse(data)
前提是你在templates文件夹下创建一个login.html文件:
django帮助我们呢省掉了打开文件的操作,我们呢只需使用下面的代码同样可以打开login.html文件:
from django.shortcuts import render
def login(request):
return render(request,'login.html')
配置模板templates的路径代码看起来简洁了很多。那么在django内部也是会寻找我们的login.html路径的,我们的login.html是在templates文件夹下的,如果在其它地方,那么django就会找不到login.html文件。我们需要对django进行配置,前面提到过settings.py文件,它在mydjango总工程目录下,我们可以找到下面的代码:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #django工程的当前目录
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')] #当前目录加上templates
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
配置静态static目录如果你有特殊情况,可以修改路径,但是你最好不要那样做!现在我们最重要的任务就是完成login.html页面了!一个login.html页面中包含很多的js文件或者css样式,所以你需要专门创建一个文件夹用来存放js或者css文件,这通常叫做静态文件,文件夹的名字django已经帮你想好了,叫做 static
。在static文件夹里面可以存放一些所有APP共享的静态文件。那么我么来看一下文件的目录:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR,'static'),
)
这样我们Ctrl+S保存重启,就会发现css和js全部引入到网页里面了,以后我们需要什么css和js,在静态文件中添加引入就可以了,注意不要随意更换静态文件的名字
,当然还有模板文件的名字
。到此所有的路都已经铺好了,接下来就是如何设计一个login.html登录页面,这涉及到HTML和CSS,当然还有JS的知识,鳄鱼君推荐学习一下:HTML教程和CSS教程。
我们知道Form表单提交的数据是POST请求,在浏览器中回车搜索属于GET请求,用户输入信息后会点击按钮提交,如果信息匹配返回给相应的页面,那么我们该怎么获取用户提交的数据呢?我们可以按照以下进行修改:
views.py# Create your views here.
from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect
#解决CSRF verification failed. Request aborted.
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def login(request):
#request包含用户的所有信息
#判断用户提交的方法
error=""
if request.method=='POST':
user=request.POST.get('user',None) #使用字典的get方法,如果不存在返回None
pwd=request.POST.get('pwd',None)
print(user,pwd)
if user=='root' and pwd=='123':
#判断用户信息是否正确
return redirect('http://www.e1yu.com') #重定向到鳄鱼教程官网
else: #用户名不正确
error="用户名或密码错误"
return render(request,'login.html',{'error':error}) #django会找到并打开login.html对error字符进行替换
login.html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<form action="/login/" method="post">
<p>
<label for="username">用户名:</label>
<input id="username" name="user" type="text"/>
</p>
<p>
<label for="pwassword">密码:</label>
<input id="password" name="pwd" type="text"/>
<input type="submit" value="登录"/>
</p>
<span style="color: rebeccapurple">{{ error }}</span> {# django会对特殊的字符船进行替换 #}
</form>
</body>
</html>
urls.pyfrom django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', views.login),
]
重新运行django程序,你就可以看到效果。用户输入正确的信息,将被重定向到鳄鱼教程的首页,输入错误会出现提示。期间可能会报错:CSRF verification failed. Request aborted.,我们在views.py中导入
from django.views.decorators.csrf import csrf_exempt
然后在自己写的login函数上面加上
@csrf_exempt
或者可以在settings.py中注释掉一行即可。这一行大概在46行左右。
'django.middleware.csrf.CsrfViewMiddleware'
选择任意一种方式即可,鳄鱼君提醒大家需要特别注意路径问题,urls.py中路径如果为login/
的话,login.html中form表单的action值就为/login/
,另一种是urls.py 中路径为login
,login.html中form表单的action值就为/login
。两者不一致就会报错:RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and you have APPEND_SLASH set. Django can’t redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/login/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.。
以上代码中,django其实会对login.html页面进行处理,它不单单是一个HTML页面,它可以写入一些django可以处理的语法字符,比方说我们刚才的{# 注释#}
、{{error }}
,django就会进行处理,自行尝试可看到效果。
一般这种登录之后会显示后台页面,可以让我们进行修改操作,而不是单单重定向到鳄鱼教程官网。我们现在在templates模板文件夹
下新建一个index.html页面,在用户登录成功之后展示给我们。这是一个简单的用户管理页面,使用for循环生成的数据:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户后台管理</title>
</head>
<body>
<div style="height: 50px;background-color: #dddddd"></div>
<table >
<thead >
<tr>
<th style="width: 50%">用户</th>
<th style="width: 50%">邮箱</th>
</tr>
</thead>
<tbody>
{% for i in USER_LIST %} {# for循环开始 #}
<tr><td>{{ i.user }}</td><td>{{ i.email }}</td></tr> {# 取字典的user值和email值,而不是用i['user'],i['email'] #}
{% endfor %} {# for循环结束 #}
</tbody>
</table>
</body>
</html>
views.py增添如下代码:USER_LIST=[
{'user':'鳄鱼君','email':'123456@qq.com',}
]
for item in range(10):
user= {'user':'鳄鱼君'+str(item),'email':str(item)+'123456@qq.com',}
USER_LIST.append(user)
def index(request):
return render(request,'index.html',{'USER_LIST':USER_LIST})
我们可以在index添加一个form表单,提交方式为POST,这样就可以动态的添加用户:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户后台管理</title>
</head>
<body>
<div style="height: 50px;background-color: #dddddd"></div>
<form action="/index/" method="post">
<input name="username" type="text" placeholder="用户名"/>
<input name="email" type="text" placeholder="邮箱"/>
<input value="添加" type="submit"/>
</form>
<table >
<thead >
<tr>
<th style="width: 50%">用户</th>
<th style="width: 50%">邮箱</th>
</tr>
</thead>
<tbody>
{% for i in USER_LIST %} {# for循环开始 #}
<tr><td>{{ i.user }}</td><td>{{i.email}}</td></tr> {# 取字典的user值和email值,而不是用i['user'],i['email'] #}
{% endfor %} {# for循环结束 #}
</tbody>
</table>
</body>
</html>
views.pyUSER_LIST=[
{'user':'鳄鱼君','email':'123456@qq.com',}
]
@csrf_exempt
def index(request):
if request.method=='POST':
#获取用户提交的数据
user=request.POST.get('username',None)
email=request.POST.get('email',None)
data={'user':user,'email':email}
USER_LIST.append(data) #添加到列表中让index页面读取
return render(request,'index.html',{'USER_LIST':USER_LIST})
特别注意路径的/和CSRF verification failed. Request aborted.。
– END –
2. 本站不保证所提供下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理!
3. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!