如何为特定模型实例设置添加、删除、更新和查看权限?

2 投票
1 回答
2232 浏览
提问于 2025-04-16 16:04

我是一名刚接触Python和Django的新手,正在开发一个Django应用。我需要管理一个叫做Foo的模型实例的权限。虽然还有其他模型实例,但权限只适用于Foo。

我在我的FooAdmin类中重写了has_add_permissionhas_delete_permission,但似乎没有任何效果。

需求:

  1. 添加Foo对象:用户必须是超级管理员。
  2. 删除Foo对象:用户必须是超级管理员。
  3. 编辑现有的Foo对象:用户必须属于ldap组'foo-edit'。如果用户属于这个组,他/她只能编辑一个字段(building)(尚未实现)。
  4. 查看Foo:如果用户属于ldap组'foo-access',那么用户只有查看权限。(待调查)
  5. 如果要添加、更新、删除或修改其他模型实例,则规则1到4不适用。

我的实现:

class FooAdmin(ModelAdmin):
  ...
  ...
  ...
  def has_add_permission(self, request):
    permissions = self.opts.app_label + '.' + self.opts.get_add_permission()
    # Other objects are fine.
    user = request.user
    if (user.has_perm('survey.add_foo') and user.is_authenticated
        and user.is_superuser):
      return True
    return False

  def has_delete_permission(self, request, obj=None):
    permissions = self.opts.app_label + '.' + self.opts.get_delete_permission()
    user = request.user
    if (user.has_perm('survey.delete_foo') and user.is_authenticated
        and user.is_superuser):
      return True
    return False

问题:

  1. 我可以创建另一个类型为Bar的实例,但无法删除我刚创建的实例。这与FooBar类型的实例没有问题。BarAdmin的实现没有管理权限的代码,而FooBarAdmin的实现则有。

    有没有办法解决这个问题,让Bar和FooBar可以再次被删除?

  2. 我该如何实现需求3和4?我可以重写has_change_permission方法来判断用户是否有修改权限。如何只给用户一个字段的编辑权限呢?

    Django似乎不支持仅查看权限。我可以创建has_view_permission(self, request)和get_model_perms(self, request)等方法,但我不确定该如何实现。我一直在查看Django的源代码,但想不出什么办法。

1 个回答

1

经过一番搜索和尝试,我终于找到了解决办法。我不太确定回答你问题的流程是什么。

  1. 首先,创建一个中间件实现(threadlocals.py),用来在一个线程中存储用户信息。

    try:
      from threading import local
    except ImportError:
      from django.utils._threading_local import local
    
    _thread_locals = local()
    def get_current_user():
      return getattr(_thread_locals, 'user', None)
    
    class ThreadLocals(object):
      """Middleware that gets various objects from the request object and
      saves them in thread local storage."""
    
      def process_request(self, request):
        _thread_locals.user = getattr(request, 'user', None)
    
  2. 接着,创建一个权限检查的工具模块,用来验证用户的权限。

    import ldap  
    from django.contrib.auth.models import User    
    from myapp.middleware import threadlocals
    
    def can_edit():
      user_obj = threadlocals.get_current_user()
      if user_obj and (is_superadmin(user_obj.username) or \
          is_part_of_group(user_obj.username, 'foo-edit')):
        return True
      return False
    
    def can_edit_selectively():
      user = threadlocals.get_current_user()
      if (user and not user.is_superuser and
          is_part_of_group(user.username, 'foo-edit')):
        return True
      return False
    
    def can_view_only():
      user_obj = threadlocals.get_current_user()
      if (user_obj and not user_obj.is_superuser and
          is_part_of_group(user_obj.username, 'foo-access') and
          not is_part_of_group(user_obj.username, 'foo-edit')):
        return True
      return False
    
    def has_add_foo_permission():
      user = threadlocals.get_current_user()
      if (user and user.has_perm('survey.add_foo') and user.is_authenticated
          and user.is_superuser):
        return True
      return False
    
    def has_delete_foo_permission():
      user = threadlocals.get_current_user()
      if (user and user.has_perm('survey.delete_foo') and user.is_authenticated
          and user.is_superuser):
        return True
      return False
    
    def is_superadmin(logged_in_user):
       admin = False
       try:
         user = User.objects.get(username=logged_in_user)
         if user.is_superuser:
           admin = True
         except User.DoesNotExist:
           pass
      return admin
    
    def is_part_of_group(user, group):
      try:
        user_obj = User.objects.get(username=user)
        if user_obj.groups.filter(name=group):
          return True
      except User.DoesNotExist:
        pass
      conn = ldap.open("ldap.corp.mycompany.com")
      conn.simple_bind_s('', '')
      base = "ou=Groups,dc=mycompany,dc=com"
      scope = ldap.SCOPE_SUBTREE
      filterstr = "cn=%s" % group
      retrieve_attributes = None
      try:
        ldap_result_id = conn.search_s(base, scope, filterstr, retrieve_attributes)
        if ldap_result_id:
          results = ldap_result_id[0][1]
          return user in results['memberUid']
      except ldap.LDAPError:
        pass
      return False
    
  3. 然后,设置管理员。在操作中会评估用户的权限。如果用户没有删除权限,那么“删除Foo”的操作就不可用。

    class FooAdmin(ModelAdmin):
    
      ...
    
      def get_actions(self, request):
        actions = super(FooAdmin, self).get_actions(request)
        delete_permission = self.has_delete_permission(request)
        if actions and not delete_permission:
          del actions['delete_selected']
        return actions
    
      def has_add_permission(self, request):
        return auth_utils.has_add_foo_permission()
    
      def has_delete_permission(self, request, obj=None):
        return auth_utils.has_delete_foo_permission()
    
      ....
    
  4. 接下来,修改init函数,在ModelForm的实现中进行调整。

     class FooForm(ModelForm):
    
       def __init__(self, *args, **kwargs):
         self.can_view_only = (auth_utils.can_view_only() and
                               not auth_utils.can_edit_selectively())
         self.can_edit_selectively = (auth_utils.can_edit_selectively() or
                                      auth_utils.can_view_only())
         if self.can_edit_selectively:
           ... Set the widget attributes to read only.
    
         # If the user has view only rights, then disable edit rights for building id.
         if self.can_view_only:
           self.fields['buildingid'].widget = forms.widgets.TextInput()
           self.fields['buildingid'].widget.attrs['readonly'] = True
         elif (auth_utils.can_edit() or auth_utils.can_edit_selectively()):
           self.fields['buildingid'].widget=forms.Select(choices=
                                                    utils.get_table_values('building'))
    
  5. 我还需要禁用那些会修改提交行的操作。

    def submit_edit_selected_row(context):
      opts = context['opts']
      change = context['change']
      is_popup = context['is_popup']
      save_as = context['save_as']
      if opts.object_name.lower() != 'foo':
        has_delete = (not is_popup and context['has_delete_permission']
                      and (change or context['show_delete']))
        has_save_as_new = not is_popup and change and save_as
        has_save_and_add_another = (context['has_add_permission'] and
                                    not is_popup and (not save_as or context['add']))
        has_save_and_continue = (context['has_add_permission'] and
                                 not is_popup and (not save_as or context['add']))
        has_save = True
      else:
        has_delete = auth_utils.has_delete_pop_permission()
        has_save_as_new = auth_utils.has_add_pop_permission()
        has_save_and_add_another = auth_utils.has_add_pop_permission()
        has_save_and_continue = (auth_utils.can_edit() or
                                 auth_utils.can_edit_selectively())
        has_save = auth_utils.can_edit() or auth_utils.can_edit_selectively()
      return {
        'onclick_attrib': (opts.get_ordered_objects() and change
                              and 'onclick="submitOrderForm();"' or ''),
        'show_delete_link': has_delete,
        'show_save_as_as_new': has_save_as_new,
        'show_save_and_add_another': has_save_and_add_another,
        'show_save_and_continue': has_save_and_continue,
        'is_popup': is_popup,
        'show_save': has_save
       }
    register.inclusion_tag('admin/submit_line.html', takes_context=True) (submit_edit_selected_row)
    
  6. 最后,我需要修改并扩展管理员的模板,其他部分保持不变。

    {% if save_on_top %} {% submit_edit_selected_row %} {% endif}
    

撰写回答