Django视图装饰访问'自我'

时间:2017-02-09 05:01:24

标签: python django decorator self

我正试图在我的装饰师中调用self,但我收到错误。首先是背景:

我有以下型号:

Car(models.Model):
   user = ForeignKey(User)
   color = models.CharField(max_length=25)

Location(models.Model):
   user = ForeignKey(User)
   city = models.CharField(max_length=25)

我希望有网址来编辑城市/颜色,如: /edit/<model-name>/<model-id>,但我想确保只有request.usermodel_instance.user相同时才能访问此内容。所以我有以下观点:

class EditView(View):
    ThisModel = Model

    def get(self, request, model_id):
        instance = self.ThisModel.objects.get(id=model_id)
        if instance.user != request.user:
            return HttpResponseForbidden("You can't do this!")
        else:
            # return form
            return render(request, 'my_template.html', context={'form':form})

    def post(request, model_id):
        instance = self.ThisModel.objects.get(id=model_id)
        if instance.user != request.user:
            return HttpResponseForbidden("You can't do this!")
        else:
            # save form
            return HttpResponse('Edit successful.')

class EditCarView(EditView):
    ThisModel = Car

class EditLocationView(EditView):
    ThisModel = Location

我想使用装饰器,而不是重复instance=...get方法共有的post行。我试过这个:

def current_user_only(func):
    def _check_curr_user(view_func):
        def _testview(self, request, model_id, *args, **kwargs):
            self.instance = self.ThisModel.objects.get(id=model_id)
            if self.instance.user != request.user:
                return HttpResponseForbidden("Forbidden.")
            else:
                return view_func(request, username, *args, **kwargs)

        _testview.__name__ = view_func.__name__
        _testview.__dict__ = view_func.__dict__
        _testview.__doc__ = view_func.__doc__

        return _testview

    return _check_curr_user(func)

在我的观点中使用它:

@method_decorator(current_user_only, name='dispatch')
EditView(View):

但是我收到错误_testview缺少一个位置参数request。如何让这个装饰工作?谢谢!

1 个答案:

答案 0 :(得分:0)

在你的情况下,我认为你必须使用, @method_decorator(current_user_only, name='dispatch') EditView(View):

您可能希望阅读Here