Django实现登录验证功能
本帖最后由 八戒你干嘛 于 2019-1-29 15:08 编辑Django实现登录验证功能:
Django对用户登录功能已经进行了封装,我们只需要简单地修改就可以了。
视图:
views.py# Create your views here.
# -*- coding: utf-8 -*-
from django.shortcuts import render,render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.template import RequestContext
from webserver.forms import UserForm,RegisterForm
import time
#登录验证
def login(req):
nowtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if req.method == 'GET':
uf = UserForm()
return render_to_response('login.html', RequestContext(req, {'uf': uf,'nowtime': nowtime }))
else:
uf = UserForm(req.POST)
if uf.is_valid():
username = req.POST.get('username', '')
password = req.POST.get('password', '')
user = auth.authenticate(username = username,password = password)
if user is not None and user.is_active:
auth.login(req,user)
return render_to_response('index.html', RequestContext(req))
else:
return render_to_response('login.html', RequestContext(req, {'uf': uf,'nowtime': nowtime, 'password_is_wrong': True}))
else:
return render_to_response('login.html', RequestContext(req, {'uf': uf,'nowtime': nowtime }))
路由:urls.pyfrom django.conf.urls import *
from webserver import views
urlpatterns = [
url(r'^login/
html页面
login.html{% load staticfiles %}
<link href="{% static "css/adstyle.css"%}" rel="stylesheet" type="text/css" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
</head>
{% if password_is_wrong %}
<script type="text/javascript" src="{%static "js/jquery-1.11.0.min.js" %}"></script>
<script type="text/javascript" src="{%static "js/alert.js" %}"></script>
<link href="{%static "css/alert.css" %}" rel="stylesheet" type="text/css" />
<script type="text/javascript">
Alert.showMsg("错误!!用户名或密码错误!");
location.href="/webserver/login/"
</script>
{% endif %}
<body>
<div class="admin-ht" style="background: url(/static/images/lo.jpg);">
<div class="adminBord">
<h1>运维管理平台</h1>
<h4>{{ nowtime }}</h4>
<form method="post" enctype="multipart/form-data" >
{% csrf_token %}
{{uf.as_p}}
<input type="submit" value="login" id="loging">
</form>
</div>
</div>
</body>
</html>
效果:
支持分享
页:
[1]