如何将PK传递给方法装饰器

时间:2020-01-25 18:00:35

标签: python django django-models decorator access-control

大家好,我正在尝试对我的视图实施某种形式的访问控制。我的程序结构如下: 1个项目有一些以外键形式绑定到它的用户。我只希望允许参与其中的人查看此项目。但是问题是我用来查询模板的数据库的PK在我的URL中,无法访问项目的用户可以简单地更改url查询并获得对他们无法访问的项目的访问权限。

我遇到了django的user_passes_test方法装饰器,并认为这正是实现此用户访问控制所需要的。

这是我想出的一些代码:

我的观点:

@method_decorator(user_passes_test(project_check(id)),name ='dispatch')
class ProjectDetailView(CreateView):

##this is actually not relavant##
  model = SalesNotation
  fields = ['sales_notes']
  exclude = ['notation_id']
  template_name = 'rnd/projects.html'
  context_object_name = 'form'
##this is actually not relavant##

  def get_context_data(self, **kwargs):
    id = self.kwargs['id']
    context = super(ProjectDetailView, self).get_context_data(**kwargs)
    context['projects'] = SalesProject.objects.filter(sales_project_id = id)

这是我的网址:

 path('projects/<int:id>/', ProjectDetailView.as_view(), name = 'rnd-projects'),

这是我的项目模型:

    class SalesProject(models.Model):
sales_project_id = models.AutoField(primary_key=True)
sales_project_name = models.CharField(max_length=100)
salesExtra = models.ManyToManyField('SalesExtra', blank=True)

这是我用来保存其他信息的扩展用户模型:

class SalesExtra(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
user_type = models.TextField(max_length=500, choices= role)
contact = models.IntegerField()
email = models.TextField(max_length=30,default = 'your email here')

这是我使用的方法修饰器:

def project_check(user,id):
return SalesProject.objects.filter(sales_project_id=id).filter(salesExtra__user=user)

但是,当我在运行服务器时收到此错误时,似乎无法简单地从URL中传递PK:

    @method_decorator(user_passes_test(project_check(id) , name='dispatch'))
TypeError: project_check() missing 1 required positional argument: 'id

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

不能。但是您可以改用UserPassesTestMixin

from django.contrib.auth.mixins import UserPassesTestMixin

class ProjectDetailView(UserPassesTestMixin, CreateView):

##this is actually not relavant##
  model = SalesNotation
  fields = ['sales_notes']
  exclude = ['notation_id']
  template_name = 'rnd/projects.html'
  context_object_name = 'form'
##this is actually not relavant##

  def get_context_data(self, **kwargs):
    id = self.kwargs['id']
    context = super(ProjectDetailView, self).get_context_data(**kwargs)
    context['projects'] = SalesProject.objects.filter(sales_project_id = id)

  def test_func(self):
    return SalesProject.objects.filter(sales_project_id=self.kwargs["id"]).filter(salesExtra__user=self.request.user)

请注意此处的test_func进行检查。 self.kwargs["id"]会给您id