首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Django实战-信息资讯-CMS后台管理-中

Django实战-信息资讯-CMS后台管理-中

作者头像
小团子
发布2019-07-18 17:00:25
5860
发布2019-07-18 17:00:25
举报
文章被收录于专栏:数据云团数据云团

Django网络应用开发的5项基础核心技术包括模型(Model)的设计,URL 的设计与配置,View(视图)的编写,Template(模板)的设计和Form(表单)的使用。

对应用中的数据在后台进行增删改查,那如何实现呢?首先,需要展示出平台有哪些内容,才知道对哪些数据进行增加、修改和删除。在展示上需要考虑,是全部一次性显示出来,还是对数据分页呢?那问题就来了,一次性全部显示出来,这样操作对于平台数据一旦有1W+,那渲染出来的数据所消耗的时间是很长,并且对数据库的查询能力也要有很高的要求。

对于在后台操作数据,是需要用户有管理员的权限才能进行增删改。通过 django 的装饰器,来自定义用户操作视图的权限。

① 在类视图中装饰

在类视图中使用为函数视图准备的装饰器时,不能直接添加装饰器,需要使用method_decorator 将其转换为适用于类视图方法的装饰器。

method_decorator 装饰器使用 name 参数指明被装饰的方法。

# 为全部请求方法添加装饰器
@method_decorator(my_decorator, name='dispatch')
class DemoView(View):
  def get(self, request):
    print('get方法')
    return HttpResponse('ok')
 
  def post(self, request):
    print('post方法')
    return HttpResponse('ok')
 
 
# 为特定请求方法添加装饰器
@method_decorator(my_decorator, name='get')
class DemoView(View):
  def get(self, request):
    print('get方法')
    return HttpResponse('ok')
 
  def post(self, request):
    print('post方法')
    return HttpResponse('ok')

② 权限

Django的权限系统,赋予 users 或 groups 中的users以权限。

from django.contrib.auth.models import Permission, ContentType

1.ContentType.model_class() : 获取当前 ContentType 类型所代表的模型类

2.ContentType.get_object_for_this_type() : 使用当前 ContentType 类型所代表的模型类做一次get查询

3.ContentType.objects.get_for_id() : 通过 id 寻找 ContentType 类型,这个跟传统的get方法的区别就是它跟 get_for_model 共享一个缓存,因此更为推荐。

4.ContentType.objects.get_for_model() : 通过 model 或者 model 的实例来寻找 ContentType 类型。

functools.wraps 定义函数装饰器

from functools import wraps
def permission_required(model):
    def decorator(viewfunc):
        @wraps(viewfunc)
        def _wrapper(request, *args, **kwargs):
            content_type = ContentType.objects.get_for_model(model)
            permissions = Permission.objects.filter(content_type=content_type)
            codenames = [content_type.app_label + "." + permission.codename for permission in permissions]
            # has_perms只能采用字符串的形式判断
            # 字符串的形式为 app_label.codename
            result = request.user.has_perms(codenames)
            if result:
                return viewfunc(request, *args, **kwargs)
            else:
                raise Http404()
        return _wrapper
    return decorator
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-07-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 数据云团 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • functools.wraps 定义函数装饰器
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档