如何用Django建立一个后台CRM系统06

权限限制(重定向)

  在我的理解中 权限限制差不多是在搞复杂一点的重定向问题

    上部分F代码不够优雅好看 重新写一个py函数 

    即已经登录过的用户不会跳转到login/register页面的限制

    装饰器decorators 的意思差不多是把一个函数当作另外一个函数的参数

      -创建一个decorators。py装饰器函数 

from django.shortcuts import redirect
from django.http import HttpResponse

def unanthenticated_user(view_func):
    def wrapper_func(request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect('home')
        else:
            return view_func(request, *args, **kwargs)
    return wrapper_func

      -在loginPage/registerPage上面@出来 

       把这两个函数当中参数传入views_function

@unanthenticated_user
def registerPage(request):
    form = CreatUserForm()
    if request.method=='POST':
        form = CreatUserForm(request.POST)
        if form.is_valid():
            form.save()
            user = form.cleaned_data.get('username')
            messages.success(request,'Accounts was created for '+ user)
            return redirect('login')
    context = {'form': form}
    return render(request,'accounts/register.html',context)

@unanthenticated_user
def loginPage(request):
    if request.method =='POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username=username,password=password)
        if user is not None:
            login(request, user)
            return redirect('home')
        else:
            messages.info(request,'Account or Password is incorrect')
    return render(request, 'accounts/login.html')

    对管理员和顾客身份的权限限制

    即管理员开发全部页面 顾客只开发部分页面

    A

    在127.0.0.1/8000/admin/group 中设置两种分组 admin 和  customer

    然后再创建两个用户分别放入小组

     -对用户权限进行限制 套入三层函数 第一层输入的参数是通过权限的分组 第二层是对应的页面

  

def allowed_user(allowed_roles= []):
    def decorators(views_func):
        def wrapper_func(request, *args, **kwargs):
            group = None
            if request.user.groups.exists():
                group = request.user.groups.all()[0].name
            if group in allowed_roles:
                return views_func(request, *args, **kwargs)
            else:
                return HttpResponse('You are not authorized to views this page')
        return wrapper_funcd
    return decorators

    -再以@的形式添加到需要限制权限的函数页面上面

@login_required(login_url='login')
@allowed_user(allowed_roles=['admin'])
def home(request):
    customer = Customer.objects.all()
    order = Order.objects.all()
    total_order = order.count()
    Delivered = Order.objects.filter(status='Delivered').count()
    Pending = Order.objects.filter(status='Pending').count()

    context = {'customer':customer,'order':order,'total_order':total_order,'Delivered':Delivered,'Pending':Pending}

    return render(request, 'accounts/home.html',context)

@login_required(login_url='login')
@allowed_user(allowed_roles=['admin'])
def customer(request, pk):

    customer = Customer.objects.get(id=pk)
    order = customer.order_set.all()
    total_order = order.count()

    myfilter = OrderFilter(request.GET, queryset=order)
    order = myfilter.qs

    context = {'customer':customer, 'order':order, 'total_order':total_order
               ,'myfilter':myfilter}

    return render(request, 'accounts/customer.html', context)

    -优化代码

    对于顾客登录HOME页面的@函数进行修改 顾客登录后看到是user页面

    -创建userPage的url 模板 函数

    -在decorator。py写入admin_only

def admin_only(views_func):
    def wrapper_func(request, *args, **kwargs):
        group = None
        if request.user.groups.exists():
            group = request.user.groups.all()[0].name
        if group == 'customer':
            return  redirect('userPage')
        if group == 'admin':
            return views_func(request,*args, *kwargs)

    return wrapper_func

    -将其@在home函数上面

@login_required(login_url='login')
@admin_only
def home(request):
    customer = Customer.objects.all()
    order = Order.objects.all()
    total_order = order.count()
    Delivered = Order.objects.filter(status='Delivered').count()
    Pending = Order.objects.filter(status='Pending').count()

    context = {'customer':customer,'order':order,'total_order':total_order,'Delivered':Delivered,'Pending':Pending}

    return render(request, 'accounts/home.html',context)

    -在对模板Navtar写if 语句  目的是不让顾客看到home 和 customer

 {% if request.user.is_staff %}
      <li class="nav-item active">
        <a class="nav-link" href="{% url 'home' %}">Dashboard</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="{% url 'products' %}">Products</a>
      </li>
  {% endif %}

 

    -对于新注册进来的顾客 我们要自动把他们分入customer组

         因此我们需要对register函数进行操作、

     -首先引入user内的models模板

from django.contrib.auth.models import Group 

     -在register函数里

      用sql把name写入分组   

        if form.is_valid():
            user = form.save()
            username = form.cleaned_data.get('username')

            group = Group.objects.get(name='customer')
            user.groups.add(group)

    新注册好的用户自动分入customer组

      

posted @ 2020-08-01 11:38  Kangkang丶  阅读(112)  评论(0编辑  收藏  举报