如何基于每个视图将参数传递给mixin

时间:2019-10-22 07:59:04

标签: python django django-views

我有一个用于管理测试用例的应用程序,这些应用程序被组织到各个项目中。我正在尝试根据每个项目设置权限,即每个用户对每个项目都有不同的权限。到目前为止,这是我想出的:

class TestProjectMember(models.Model):
    """Per project permissions - a role can be set for each user for each project"""
    member_name = models.ForeignKey(User, on_delete=models.SET_NULL)
    project = models.ForeignKey(TestProject, on_delete=models.CASCADE)
    member_role = models.CharField(choices=Choices.roles)

class TestCase(models.Model):
    """Test cases"""
    tc_title = models.CharField(max_length=500, unique=True)
    tc_project = models.ForeignKey(TestProject, on_delete=models.CASCADE)

class TestProject(models.Model):
    """Projects"""
    project_name = models.CharField(max_length=200)
    project_desc = models.CharField(max_length=500)



class TestCaseEditHeader(View):

    def get(self, request, pk):
        case = get_object_or_404(TestCase, id=pk)
        if self.get_perm(case.tc_project, request.user, 'TA'):
            form = TestCaseHeaderForm(instance=case)
            context = {'case': case, 'form': form}
            return render(request, 'test_case/tc_header_edit.html', context)
        else:
            return redirect('case_list')

        def get_perm(self, curr_project, curr_user, perm):
            model_perm = TestProjectMember.objects.filter(member_name=curr_user, 
                project=curr_project).values_list('member_role', flat=True)
            if perm in model_perm:
                return True
            return False

可以,但是有点笨拙。我必须从每个视图的每个get()或post()方法调用get_perm()方法。更好的解决方案可能是混合。我难过的是如何将所需角色传递给每个视图的mixin。对于每个视图,用户都必须具有一个必需的角色,该角色必须能够将视图用于测试用例所属的项目。我如何告诉mixin,哪个视图需要哪个特定角色?

1 个答案:

答案 0 :(得分:1)

您可以将其设置为类属性。

请注意,您的查询效率很低;您只需要直接请求所需的烫发即可。

form_for(resource, as: resource_name, url: user_registration_path)

然后在具体的类中设置属性:

class TestPermMixin:
    def get_perm(self, curr_project, curr_user):
        return TestProjectMember.objects.filter(
             member_name=curr_user, project=curr_project, member_role=self.perm
        ).exists()