Django基础(五)

Django admin 自带的验证:

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

@login_required        #只有用户登陆之后才执行下面操作
def index(request):
    return render(request,'index.html')

def acc_login(request):    #验证用户登陆函数
    if request.method == 'POST':
        user = authenticate(username=request.POST.get('username'),password=request.POST.get('password'))
        if user is not None:        # 如果验证成功
            login(request,user)
            return HttpResponseRedirect('/')
        else:
            login_err = u'用户名或密码错误'
            return render(request,'login.html',{'login_err':login_err})
    return render(request,'login.html')

def acc_logout(request):
    logout(request)
    return HttpResponseRedirect('/')

 

 

Django 分页

后端代码

def customers(request):
    customers_set = models.Customer.objects.all()
    # 生成分页实例,第一个参数为query_set对象,第二个参数为每页显示多少条数据
    paginator = Paginator(customers_set, 1)
    # 从请求中获取页码
    page = request.GET.get("page")
    try:
        customers_iter = paginator.page(page)
    # 如果获取的page不是数字,就默认返回第一页
    except PageNotAnInteger:
        customers_iter = paginator.page(1)
    # 如果获取的page不存在,就默认返回最后一页
    except EmptyPage:
        customers_iter = paginator.page(paginator.num_pages)

    return render(request, "crm/customers.html", {"customers": customers_iter})

 

自定义template tags

首先创建目录和文件

polls/            #app名,在app下创建目录
    __init__.py
    models.py
    templatetags/        #目录名称,必须是这个名称
        __init__.py
        poll_extras.py        # 自定义tag文件
    views.py

poll_extra.py

from django import template
from django.utils.html import format_html


register = template.Library()

@register.simple_tag    # 注册方法
def guess_page(current_page,loop_num):
offset
= abs(current_page - loop_num)
if offset < 3:
if current_page == loop_num:
page_els
= '''<li class="active"><a href="?page=%s">%s</a></li>''' %(loop_num,loop_num)
else:
page_els
= '''<li class=""><a href="?page=%s">%s</a></li>''' %(loop_num,loop_num)
return format_html(page_els)
else:
return ''

 前端页面引用:

{% load poll_extras %}  #tag文件名

 

权限管理

Django 自带有基本的权限管理,但是粒度和限制的纬度都只是针对具体的表。

写权限注意事项:

  1. 权限系统的设计对开发者,用户要实现透明
  2. 权限要易扩展,灵活
  3. 权限要能实现非常小的粒度控制,甚至细致到一个按键某个用户是否能操作。

想对一个功能实现权限控制,要做到只能在views方法上加一个装饰器就行了,比如:

@check_permission
@login_required
def customer_detail(request,customer_id):
    customer_obj = models.Customer.objects.get(id=customer_id)
    customer_form = forms.CustomerDetailForm(instance=customer_obj)
 
    if request.method == 'POST':
        customer_form = forms.CustomerDetailForm(request.POST,instance=customer_obj)
        if customer_form.is_valid():
            customer_form.save()
            parent_base_url = '/'.join(request.path.split('/')[:-2])
            print("url:",parent_base_url )
            return  redirect(parent_base_url)
        else:
            print(customer_form.errors)
    return  render(request,'crm/customer_detail.html',{'customer_form':customer_form})

 

自己写一个权限控制

from django.core.urlresolvers import resolve
from django.shortcuts import render,redirect

perm_dic = {
    'view_customer_list': ['customer_list','GET',[]],
    'view_customer_info': ['customer_detail','GET',[]],
    'edit_own_customer_info': ['customer_detail','POST',['test']],
}

def perm_check(*args,**kwargs):
    request = args[0]
    url_resovle_obj = resolve(request.path_info)
    current_url_namespace = url_resovle_obj.url_name
    #app_name = url_resovle_obj.app_name #use this name later
    print("url namespace:",current_url_namespace)
    matched_flag = False # find matched perm item
    matched_perm_key = None
    if current_url_namespace is not None:#if didn't set the url namespace, permission doesn't work
        print("find perm...")
        for perm_key in perm_dic:
            perm_val = perm_dic[perm_key]
            if len(perm_val) == 3:#otherwise invalid perm data format
                url_namespace,request_method,request_args = perm_val
                print(url_namespace,current_url_namespace)
                if url_namespace == current_url_namespace: #matched the url
                    if request.method == request_method:#matched request method
                        if not request_args:#if empty , pass
                            matched_flag = True
                            matched_perm_key = perm_key
                            print('mtched...')
                            break #no need looking for  other perms
                        else:
                            for request_arg in request_args: #might has many args
                                request_method_func = getattr(request,request_method) #get or post mostly
                                #print("----->>>",request_method_func.get(request_arg))
                                if request_method_func.get(request_arg) is not None:
                                    matched_flag = True # the arg in set in perm item must be provided in request data
                                else:
                                    matched_flag = False
                                    print("request arg [%s] not matched" % request_arg)
                                    break #no need go further
                            if matched_flag == True: # means passed permission check ,no need check others
                                print("--passed permission check--")
                                matched_perm_key = perm_key
                                break

    else:#permission doesn't work
        return True

    if matched_flag == True:
        #pass permission check
        perm_str = "crm.%s" %(matched_perm_key)
        if request.user.has_perm(perm_str):
            print("\033[42;1m--------passed permission check----\033[0m")
            return True
        else:
            print("\033[41;1m ----- no permission ----\033[0m")
            print(request.user,perm_str)
            return False
    else:
        print("\033[41;1m ----- no matched permission  ----\033[0m")
def check_permission(func):

    def wrapper(*args,**kwargs):
        print("---start check perms",args[0])
        if not perm_check(*args,**kwargs):
            return render(args[0],'crm/403.html')
        return func(*args,**kwargs)
        #print("---done check perms")
    return wrapper
posted @ 2016-06-02 19:07  binges  阅读(281)  评论(0编辑  收藏  举报