urls
path('index/',views.index), re_path(r'^$',views.index),
无需再域名后添加index即可访问主页
views
from django.contrib import auth
from django.http import JsonResponse
def login(request): user_info = {'user': None, 'msg': None} if request.method == 'POST': user = request.POST.get('user') pwd = request.POST.get('pwd') captcha = request.POST.get('captcha') if captcha.upper() == request.session['code_str'].upper(): user = auth.authenticate(username=user, password=pwd) if user: auth.login(request, user) user_info['user'] = user.username else: user_info['msg'] = '账号、密码错误' else: user_info['msg'] = '验证码错误' return JsonResponse(user_info) # 无需反序列化 return render(request, 'login.html')
用户经过auth验证后,验证对象只能命名为user,通过login赋值到request中(变成全局变量,模板和试图都能调用request.user的所有属性),user即为存储在数据库Userinfo表中的存储对象。
前端
<ul class="nav navbar-nav navbar-right">
{% if request.user.is_authenticated %} #通过后端的用户验证判断,如果验证完即显示个人主页和设置,未通过验证显示登陆与注册
<li><a href="/{{ request.user.username }}/"><span class="glyphicon glyphicon-user"></span> {{ request.user.username }}</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">用户设置<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">修改密码</a></li>
<li><a href="#">修改头象</a></li>
<li><a href="/logout/">注销</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</li>
{% else %}
<li><a href="/login/">登陆</a></li>
<li><a href="/register/">注册</a></li>
{% endif %}
</ul>
重点:
1、通过auth校验后,user对象在前后端的调用
user = auth.authenticate(username=user, password=pwd) if user: auth.login(request, user)
{% if request.user.is_authenticated %}
2、admin组件的使用
Django内部的一个组件:后台数据管理组件(web页面),协议名/admin/
需要用超级用户登陆,创建超级用户python manage.py createsuperuser
在app文件下的admin生成对象
from django.contrib import admin # Register your models here. from app01 import models admin.site.register(models.UserInfo) admin.site.register(models.Blog) admin.site.register(models.Article) admin.site.register(models.Tag) admin.site.register(models.Category) admin.site.register(models.Article2Tag) admin.site.register(models.ArticleUpDown) admin.site.register(models.Comment)