在users模块的views.py中写登录函数,然后在urls.py中引用这个函数,实现登录逻辑。
users > views.py 代码:
from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login # Create your views here. def user_login(request): if request.method == 'GET': return render(request, 'login.html', {}) if request.method == 'POST': user_name = request.POST.get('username', '') pass_word = request.POST.get('password', '') # 成功返回user,失败返回None user = authenticate(username=user_name, password=pass_word) if user is not None: login(request, user) # 直接登录 return redirect('home') else: return render(request, 'login.html', {'msg': '用户名或密码错误。'})
urls.py中的代码:
from django.contrib import admin from django.urls import path import xadmin from django.views.generic import TemplateView from users.views import user_login urlpatterns = [ path('xadmin/', xadmin.site.urls), path('', TemplateView.as_view(template_name='index.html'), name='home'), # path('login/', TemplateView.as_view(template_name='login.html'), name='login'), path('login/', user_login, name='login'), ]
修改index.html中的登录部分,添加登录判断:
<div class="wp"> <div class="fl"><p>服务电话:<b>33333333</b></p></div> <!--登录后跳转--> {% if request.user.is_authenticated %} <div class="personal"> <dl class="user fr"> <dd>bobby<img class="down fr" src="/static/images/top_down.png"/></dd> <dt><img width="20" height="20" src="/static/media/image/2016/12/default_big_14.png"/> </dt> </dl> <div class="userdetail"> <dl> <dt><img width="80" height="80" src="/static/media/image/2016/12/default_big_14.png"/> </dt> <dd> <h2>django</h2> <p>bobby</p> </dd> </dl> <div class="btn"> <a class="personcenter fl" href="usercenter-info.html">进入个人中心</a> <a class="fr" href="/logout/">退出</a> </div> </div> </div> {% else %} <a style="color:white" class="fr registerbtn" href="/register/">注册</a> <a style="color:white" class="fr loginbtn" href="/login/">登录</a> {% endif %} </div>