django 内置验证登录模块(auth login logout authenticate)测试

index页加装饰器@login_required需要登陆才能查看
user= authenticate(username=username,password=password)返回user对象
若返回user对象,登陆login(request,user),之后可以访问index

views.py

from django.contrib.auth.decorators import login_required
from django.contrib.auth import  login,authenticate,logout

@login_required
def index(request):
    return render(request,'index.html')

def accounts_login(request):
    if request.method=='GET':

        return  render(request,'login.html')
    else:
        username=request.POST.get('username')
        password=request.POST.get('password')
        user= authenticate(username=username,password=password)
        if user:
            login(request,user)
            print("OK................")
            return redirect('/index')
        else:
            err_msg="loging error"
            return render(request, 'login.html',{'err_msg':err_msg})

def accounts_logout(request):
    logout(request)
    return redirect('/accounts/login')

urls.py

@login_required 默认登录页为accounts/login/

from django.conf.urls import url
from django.contrib import admin
from app01 import  views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^accounts/login/', views.accounts_login),
        url(r'^accounts/logout/', views.accounts_logout),

]

login.html

可以调用form,这里简单测试未调用




    
    Title



{% csrf_token %}
username
password
{% if err_msg %}
{{ err_msg }}
{% endif %}

index.html 显示用户




    
    Title


{% if request.user.is_authenticated %}
{{ request.user }}
{% endif %}
登陆后退出
退出

######################################33

extra
models.py中,用的外键补充User

class UserInfo(models.Model):
    user=models.OneToOneField(User)
    name=models.CharField('姓名',max_length=32)

    def __str__(self):
        return self.name

{{ request.user }}显示的是User模块中的user
若需显示其他信息直接
{{request.user.userInfo.nane}}即可

转载于:https://blog.51cto.com/13606158/2083876

你可能感兴趣的:(django 内置验证登录模块(auth login logout authenticate)测试)