当前位置:  开发笔记 > 编程语言 > 正文

在Django中查看权限

如何解决《在Django中查看权限》经验,为你挑选了2个好方法。

由于django admin在其auth中有三个权限:添加,更改,删除!我想在管理面板中添加此身份验证中的查看权限.我知道我必须自定义权限才能在'auth |权限|查看权限'中添加查看权限以查看所有条目!

方式:

[X] 1.在默认权限列表中添加"查看"

#./contrib/auth/management/init.py
def _get_all_permissions(opts):

    "Returns (codename, name) for all permissions in the given opts."
    perms = []
    for action in ('add', 'change', 'delete', 'view'):

        perms.append((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw)))

    return perms + list(opts.permissions)

[X] 2.测试'视图'权限被添加到所有模型

run manage.py syncdb

我确认现在为auth_permissions表中的所有表添加了视图权限

[X] 3.将"get_view_permission"添加到默认模型类.

将get_view_permission添加到模型类.您可以在./db/models/options.py文件中找到它.管理类将在下一步中使用它.

def get_view_permission(self):

    return 'view_%s' % self.object_name.lower()

[X] 4.将"has_view_permission"添加到默认管理类

为了保持一致,我要将"has_view_permission"添加到系统中.看起来它应该在contrib/admin/options.py中的某个地方.确保用户具有更改权限,然后自动隐含查看权限.

# /contrib/admin/options.py
# Added has_view_permissions
def has_view_permission(self, request, obj=None):

    """
    Returns True if the given request has permission to change or view
    the given Django model instance.


    If obj is None, this should return True if the given request has
    permission to change *any* object of the given type.
    """
    opts = self.opts
    return self.has_change_permission(request, obj) or \

        request.user.has_perm(opts.app_label + '.' + opts.get_view_permission())


# modified get_model_perms to include 'view' too.
# No idea where this may be used, but trying to stay consistent
def get_model_perms(self, request):

    """
    Returns a dict of all perms for this model. This dict has the keys
    add, change, and delete and view mapping to the True/False
    for each of those actions.
    """
    return {

        'add': self.has_add_permission(request),
        'change': self.has_change_permission(request),
        'delete': self.has_delete_permission(request),
        'view': self.has_view_permission(request),

    }


# modified response_add function to return the user to the mode list
# if they added a unit and have view rights
...

    else:

        self.message_user(request, msg)

        # Figure out where to redirect. If the user has change permission,
        # redirect to the change-list page for this object. Otherwise,
        # redirect to the admin index.
        #if self.has_change_permission(request, None):
        if self.has_change_permission(request, None) or self.has_view_permission(request, None):

            post_url = '../'

        else:

            post_url = '../../../'

        return HttpResponseRedirect(post_url)

    # modified the change_view function so it becomes the details
    # for users with view permission

        #if not self.has_change_permission(request, obj):
        if not (self.has_change_permission(request, obj) or (self.has_view_permission(request, obj) and not request.POST)):

            raise PermissionDenied

        # modified the changelist_view function so it shows the list of items
        # if you have view permissions

def changelist_view(self, request, extra_context=None):

            "The 'change list' admin view for this model."
            from django.contrib.admin.views.main import ChangeList, ERROR_FLAG
            opts = self.model._meta
            app_label = opts.app_label
            #if not self.has_change_permission(request, None):
            if not (self.has_change_permission(request, None) or self.has_view_permission(request, None)):

                raise PermissionDenied

[X] 5.如果用户具有查看权限,则更新默认模板以列出模型

我修改了contrib/admin/templates/admin/index.html中的默认模板.这也可以通过将文件复制到本地模板目录来处理.我对两者进行了更改,因此如果稍后的升级会覆盖我的更改,我会有一份副本.

{% for model in app.models %}

    
    {% if model.perms.change %}

        {{ model.name }}

    {% else %}

        {% if model.perms.view %}

            {{ model.name }}

        {% else %}

            {{ model.name }}

        {% endif %}

    {% endif %}

[X] 6.确认用户可以"查看"但不能"更改"模型

找到contrib/admin/templatetags/admin_modify.py似乎控制保存/保存和继续按钮出现与否.将"保存"字段更改为默认值始终为True,以检查上下文和权限.用户应该能够保存,如果他们有更改或添加权限.

'show_save': (change and context['has_change_permission']) or (context['add'] and context['has_add_permission'])

[X] 7.如果用户正在查看项目,请删除"保存并添加另一个"按钮

再次修改了contrib/admin/templatetags/admin_modify.py.我不知道'save_as'是什么意思所以也许我打破了一些东西,但它似乎有效.

#'show_save_and_add_another': context['has_add_permission'] and
# not is_popup and (not save_as or context['add']) ,
'show_save_and_add_another': not is_popup and
    (( change and context['has_change_permission']) or (context['add'] and context['has_add_permission']))
    and
    (not save_as or context['add']),

[X] 8.修改"查看"权限,使表单只读

如果用户具有"查看"权限和"更改"权限,则不执行任何操作.更改覆盖视图.

如果用户具有"查看"权限而没有"更改",则更改默认表单并将DISABLED或READONLY属性添加到表单元素.并非所有浏览器都支持此功能,但出于我的目的,我可以要求用户使用正确的浏览器.[已禁用/只读示例] [1]

发现并非所有浏览器都尊重"readonly",因此它将一些控件设置为readonly,其他控件设置为disabled.这允许用户在需要时从文本控件复制数据.

#/django/contrib/admin/templates/admin/change_form.html


{# JavaScript for prepopulated fields #}
{% prepopulated_fields_js %}


{% if has_view_permission and not has_change_permission %} {% endif %}

答案源:我如何修改的Django打造"查看"的权限?

问题:按照上面的答案完成后我可以看到这个127.0.0.1:8000/en-us/admin/页面只读**但用户中的用户不可见127.0.0.1:8000/en-us/管理员/用户.需要帮忙!**



1> pcoronel..:

将"查看"权限添加到默认权限列表

您的解决方案有效,但您应该尽可能避免编辑源代码.在框架内有几种方法可以实现这一目标:

1. 在以下期间添加权限 post_syncdb():

在your_app/management /下的文件中

from django.db.models.signals import post_syncdb
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission

def add_view_permissions(sender, **kwargs):
    """
    This syncdb hooks takes care of adding a view permission too all our 
    content types.
    """
    # for each of our content types
    for content_type in ContentType.objects.all():
        # build our permission slug
        codename = "view_%s" % content_type.model

        # if it doesn't exist..
        if not Permission.objects.filter(content_type=content_type, codename=codename):
            # add it
            Permission.objects.create(content_type=content_type,
                                      codename=codename,
                                      name="Can view %s" % content_type.name)
            print "Added view permission for %s" % content_type.name

# check for all our view permissions after a syncdb
post_syncdb.connect(add_view_permissions)

每当您发出'syncdb'命令时,都可以检查所有内容类型以查看它们是否具有"查看"权限,如果没有,则创建一个.

消息来源:Nyaruka博客

2.将权限添加到Meta权限选项:

在每个模型下,您可以在其Meta选项中添加以下内容:

class Pizza(models.Model):
    cheesiness = models.IntegerField()

    class Meta:
        permissions = (
            ('view_pizza', 'Can view pizza'),
        )

这将完成与1相同的操作,除非您必须手动将其添加到每个类.

3. 在Django 1.7中新建,添加Meta default_permissions选项的权限:

在Django 1.7中,他们添加了default_permissions Meta选项.在每个模型下,您都可以在default_permissions选项中添加"view":

class Pizza(models.Model):
    cheesiness = models.IntegerField()

    class Meta:
        default_permissions = ('add', 'change', 'delete', 'view')



2> MoiTux..:

Django 2.1添加了对默认权限的查看权限.下面的解决方案可能适用于早期版本的Django. https://docs.djangoproject.com/en/2.1/releases/2.1/


这是在Django 1.6.2中测试的工作解决方案

[X] 1. Added 'view' to default permission list:好的
[X] 2. Test the 'view' permission is added to all models:好的

[X] 3. Add "get_view_permission" to default model class. 再也没用了:

def get_add_permission(self):
    """
    This method has been deprecated in favor of
    `django.contrib.auth.get_permission_codename`. refs #20642
    """
    warnings.warn(
        "`Options.get_add_permission` has been deprecated in favor "
        "of `django.contrib.auth.get_permission_codename`.",
        PendingDeprecationWarning, stacklevel=2)
    return 'add_%s' % self.model_name

这就是所有这些方法的情况 get_foo_permission

[X] 4. Add "has_view_permission" to default admin class 应该:

def has_view_permission(self, request, obj=None):
    """
    Returns True if the given request has permission to change or view
    the given Django model instance.


    If obj is None, this should return True if the given request has
    permission to change *any* object of the given type.
    """
    opts = self.opts
    codename = get_permission_codename('view', opts)
    return self.has_change_permission(request, obj) or \
        request.user.has_perm("%s.%s" % (opts.app_label, codename))

如果模型是内联的,请检查其右侧,因此需要了解正确的视图

def get_inline_instances(self, request, obj=None):

    ...

    if not (inline.has_add_permission(request) or
            inline.has_change_permission(request, obj) or
            inline.has_delete_permission(request, obj) or
            inline.has_view_permission(request, obj)):  # add the view right
        continue

    ...

修改get_model_perms为包含'view',在同一个想法中做这个:

def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):

    ...

    context.update({

        ...

        'has_view_permission': self.has_view_permission(request, obj), # add the view right

        ...

    })

    ....

允许"右视图"呈现页面(一个对象)并禁用"右视图"以保存在页面上完成的修改 [X] 8. Modify "view" permission to make form read only

@csrf_protect_m
@transaction.atomic
def change_view(self, request, object_id, form_url='', extra_context=None):
    "The 'change' admin view for this model."
    model = self.model
    opts = model._meta

    obj = self.get_object(request, unquote(object_id))

    # addthe view right
    if not (self.has_view_permission(request, obj) or
            self.has_change_permission(request, obj)):
        raise PermissionDenied

    ...

    inline_instances = self.get_inline_instances(request, obj)
    # do not save the change if I'm not allowed to:
    if request.method == 'POST' and self.has_change_permission(request, obj):
        form = ModelForm(request.POST, request.FILES, instance=obj)

    ...

允许"右视图"呈现页面(所有对象的列表)

@csrf_protect_m
def changelist_view(self, request, extra_context=None):
    """
    The 'change list' admin view for this model.
    """
    from django.contrib.admin.views.main import ERROR_FLAG
    opts = self.model._meta
    app_label = opts.app_label
    # allow user with the view right to see the page
    if not (self.has_view_permission(request, None) or
            self.has_change_permission(request, None)):
        raise PermissionDenied

    ....

[X] 5. Update default template to list models if user has view permission:好的,但要避免修改html模板,请编辑此文件:contrib/admin/site.py

class AdminSite(object):

    @never_cache
    def index(self, request, extra_context=None):

        ...

        # add the view right
        if perms.get('view', False) or perms.get('change', False):
        try:
            model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
        except NoReverseMatch:
            pass

        ...

    def app_index(self, request, app_label, extra_context=None):

        ...

        # add the view right
        if perms.get('view', False) or perms.get('change', False):
            try:
                model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
            except NoReverseMatch:
                pass

        ...

[X] 6. Confirm user can "view" but not "change" the model并且[X] 7. Remove "Save and Add another" button if user is viewing an item:应该没问题,但我做到了:

'show_save_as_new': context['has_add_permission'] and not is_popup and change and save_as,
'show_save': context['has_change_permission'],

[X] 8.修改"查看"权限,使表单只读:好的,但我有另一个解决方案见上文

推荐阅读
跟我搞对象吧
这个屌丝很懒,什么也没留下!
Tags | 热门标签
RankList | 热门文章
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有