一、应用基本配置
1、在根目录下新建account应用。python manage.py startapp account
2、在项目根目录的项目目录的setting下的INSTALLED_APPS中添加 ‘account’
3、在项目根目录的项目目录的url.py中进行URL配置。添加
url(r'^account/',include('account.urls',namespace='account')),
注意:将app_name=‘account’写在account.urls中
4、在account中建立urls.py文件。并添加代码
from django.conf.urls import url
from . import viewsfrom django.conf import settingsurlpatterns=[url(r'^login/$',views.user_login,name='user_login'),
]
此处必须加‘.’.因为这个list中只有一个元素。否则系统会误解。
views.user_login意味着必须在view.py中创建一个名为user_login的函数来响应请求。
二、设计用户登录过程
1、在./account中建立forms.py文件,专门用于存放各种与表单有关的类。编写
from django import formsclass LoginForm(forms.Form):username=forms.CharField()password=forms.CharField(widget=forms.PasswordInput)
login=LoginForm() 创建未绑定的对象
dir(login)查看可用方法
主要关注以下几种方法、属性
- cleaned_data:以字典形式返回你注册的用户和密码
- is_bound:判断用户是否绑定
- is_vaild():判断输入的用户和密码是否符合格式要求
2、编写用户登录的视图函数,修改 account 应用下的 views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth import authenticate,login
from .forms import LoginForm# Create your views here.def user_login(request):if request.method=='POST':login_form=LoginForm(request.POST)if login_form.is_valid():#判断表单数据是否符合要求(比如不能为空之类的)cd=login_form.cleaned_datauser=authenticate(username=cd['username'],password=cd['password'])if user:login(request,user)return HttpResponse('Welcome Boys and Girls,you have logined successfully...')else:return HttpResponse('sorry,your input is error...')if request.method=='GET':login_form=LoginForm()return render(request,'account/login.html',{'form':login_form})
3、编写在./templates/account/login.html中。
{%extends 'base.html'%}
{%block title%}登录{%endblock%}{%block content%}
<div class="row text-center vertical-middle-sm"><h1>Login</h1><p>input your username and password</p><form action="." class="form-horizontal" method="post">{%csrf_token%}{{form.as_p}}<input type="submit" value="Login"></form>
</div>
{%endblock%}
{%csrf_token%}
这个必须有,只要在 form 标签内就 OK。保证了前端可以通过 POST 方式提交数据。{{form.as_p}}
实例对象的 as_p方法,使得表单数据呈现为一系列p标签,类似有 as_ul、as_table。
此时在网址中输入http://localhost:8080/account/login 即可看到登录界面
参考自:https://blog.csdn.net/lzw2016/article/details/80425242