Django实现登录验证功能

首先给大家推荐一下我老师大神的人工智能教学网站。教学不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵黄段子!点这里可以跳转到网站

Django实现登录验证功能
Django实现登录验证功能:
Django对用户登录功能已经进行了封装,我们只需要简单地修改就可以了。
视图:
views.py

# Create your views here.# -*- coding: utf-8 -*-from django.shortcuts import render,render_to_responsefrom django.http import HttpResponseRedirectfrom django.contrib import authfrom django.template import RequestContextfrom webserver.forms import UserForm,RegisterFormimport 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.py

from django.conf.urls import *from webserver import views urlpatterns = [    url(r'^login/$',views.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>

效果:

效果:

点这里可以跳转到人工智能网站

发表评论