在Django

时间:2016-11-02 12:55:49

标签: python django django-views

我有一个基于类的视图,由其他视图继承:

class EditProfileAttribute(View):
    template_name = 'mytemplate.html'
    ThisModel = models.Model
    def get(request, model_id):
        instance = self.ThisModel.objects.get(id=model_id)
        if instance.user != request.user:
            return HttpResponseForbidden("Forbidden.")
        # add form here
        return render(request, self.template_name, {'model_id':model_id})

    def post(request, model_id):
        instance = self.ThisModel.objects.get(id=model_id)
         if instance.user != request.user:
             return HttpResponseForbidden("Forbidden.")
         # do some editing here, save forms, etc.
         return HttpResponse("Edited")

class EditAddressView(EditProfileAttributeView):
        ThisModel = Address

class EditLinkView(EditProfileAttributeView):
        ThisModel = Link

现在在我的models.py文件中:

class Address(models.Model):
    user = models.ForeignKey(User)
    address = models.TextField(max_length=100)

class Link(models.Model):
    from_user = models.ForeignKey(User, related_name='from_link')
    to_user = models.ForeignKey(User, related_name='to_link')

课程EditAddressView有效,因为用户字段明确地称为user,但课程EditLinkView没有,因为它需要instance.from_user而不是instance.user。 (我们只能说我不能重命名from_user)。

我想做的是将instance.user != request.user部分转换为不需要语法user的装饰器,但我无法弄清楚如何引用{ {1}}。

同时,这使我不会对self.ThisModelget重复相同的方法。

我想要的甚至可能吗?

1 个答案:

答案 0 :(得分:3)

您可以使用另一个class属性来存储用户字段的名称,然后使用get_attr来获取方法中的值。

如果您想避免在getpost中复制代码,请将公共代码计入辅助方法,或改为覆盖dispatch

class EditProfileAttribute(View):
    ThisModel = models.Model
    user_field_name = 'user'

    def dispatch(self, request, *args, **kwargs):
         self.instance = self.ThisModel.objects.get(id=kwargs['model_id'])
         if getattr(self.instance, self.user_field_name) != request.user:
             return HttpResponseForbidden("Forbidden.")
         # calling super() will call get() or post() as appropriate
         return super(EditProfileAttribute, self).dispatch(request, *args, **kwargs)