django網頁按鈕權限管理

最近完成這樣的一個需求,比如說一個網頁有幾個按鈕(添加,編輯,刪除,查看),張三用戶可以訪問這幾個按鈕,李四隻能查看(沒有其它權限),怎麼辦?我相信對於初學者來說,完成這樣的需求,確實有點難度,作者也是折騰了2天,才懂的一點皮毛,在這裏非常感謝我的同事雪姐,耐心的給我講解。言歸正傳,把這個流程跟大家分享一下.(高手勿噴)


首先設計表結構

創建一個用戶表,並且做了一對一關聯django user表

1.自定義用戶表

from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
#自定義用戶表
class Userinfo(models.Model):
    user = models.OneToOneField(User) #關聯django user表
    username = models.CharField(max_length=100)
    password = models.CharField(max_length=100)


    def __unicode__(self):
        return self.username


2.自定義權限表

class quanxian(models.Model):
    shuoming=models.CharField(max_length=100)
    def __unicode__(self):
        return self.shuoming
    class Meta:
        permissions = (
            ('edit', u'編輯權限'),
            ('add', u'添加權限'),
            ('DEL',u'刪除權限'),
            ('list',u'查看權限'),
        )


3.views.py定義一個login視圖方法

from test01.models import Userinfo
from django import forms
from django.contrib import auth
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.template import RequestContext


# Create your views here.
class UserForm(forms.Form):
    username = forms.CharField(label="user",max_length=100)
    password = forms.CharField(label="passwd",widget=forms.PasswordInput())
def index(request):


    return render_to_response('index.html')


def login(request):
    if request.method == 'POST':
        uf = UserForm(request.POST)
        if uf.is_valid():


            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            print username,password,"[*******]"

           

            user1 = authenticate(username=username, password=password)
            is_add = True if user1.has_perm('test01.add') else False 
            print 'user1--->',user1,user1.has_perm('test01.add'), is_add
            if user1:
                return render_to_response('index.html',locals(), context_instance=RequestContext(request))
            else:
                return HttpResponseRedirect('/login/')
    else:
        uf = UserForm()
    return render_to_response('login.html',{'uf':uf})

4.在admin.py註冊models.py裏的表

from django.contrib import admin
from test01 import models
admin.site.register(models.quanxian)
admin.site.register(models.Userinfo)

5.urls.py

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

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/$',views.index),

    url(r'^$', views.login, name='login'),
]

6.初始化數據表,創建後臺admin管理員

python manage.py  makemigrations

python manage.py  migrate

創建後臺admin管理員


bogon:model_test will.xin$ python manage.py createsuperuser

Username (leave blank to use 'will.xin'): admin

Email address: 

Password: 

Password (again): 

Superuser created successfully.


7.登錄admin後臺,創建用戶

http://127.0.0.1:8000/admin/



8.前端頁面

vim login.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>登錄</title>
</head>
 <!--style type="text/css">
    body{color:#efd;background:#453;padding:0 5em;margin:0}
    h1{padding:2em 1em;background:#675}
    h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em}
    p{margin:1em 0}
  </style-->
<body>
<h1>登錄頁面:</h1>
<form method = 'post' enctype="multipart/form-data">
    `uf`.`as_p`
    <input type="submit" value = "ok" />
</form>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>

{% if is_add %}
    <button>編輯</button>
    <button>添加</button>
    <button>刪除</button>
{% else %}
    <button>查看</button>
{% endif %}


<div>歡迎{{ username }} 登錄</div>
</body>
</html>

9.測試

首先用zhangsan用戶登錄


lisi用戶登錄後





大功告成

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章