Django实现登录验证功能

Django实现登录验证功能
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.py

from django.conf.urls import *
from webserver import views

urlpatterns = [
    url(r'^login/$',views.login),
]



html 页面
login.html
{% load staticfiles %}



    
    Login

{% if password_is_wrong %}
    
    
    
    
{% endif %}

    

运维管理平台

{{ nowtime }}

{% csrf_token %} {{uf.as_p}}


效果:


效果:

Django实现登录验证功能_第1张图片

Django实现登录验证功能_第2张图片


你可能感兴趣的:(Django)