Django更新/删除视图。处理用户权限

时间:2016-09-05 15:25:57

标签: django django-models django-views django-class-based-views django-generic-views

models.py

class Punch(models.Model):
ro_number = models.IntegerField()
flag = models.FloatField(max_length=10)
actual = models.FloatField(max_length=10)
description = models.CharField(max_length=100, blank=True)
user = models.ForeignKey(User)
created_on = models.DateTimeField(auto_now_add=True)

def efficiency(self):
    return '%.2f' % (float(self.flag)/float(self.actual)*100)

def __str__(self):
    return str(self.ro_number)

urls.py

url(r'^flags/update/(?P<pk>[0-9]+)/$', views.PunchEdit.as_view(), name='update_flags'),

view.py

class PunchEdit(views.LoginRequiredMixin,
            UpdateView,):
model = Punch
fields = ['ro_number', 'flag', 'actual', 'description']
template_name = 'free/home.html'

def get_success_url(self):
    pass

我试图弄清楚如何允许用户只编辑他们创建的打孔对象。每次创建Punch对象时,它都会保存哪个用户使用外键关系创建了打孔。 (在未显示的视图中完成)

现在,如果您输入类似 mywebsite.com/punch/update/(pk)/ 的内容,用户可以在任何打孔对象的pk中写入并更新其信息。

所以我的问题是..当使用基于类的通用更新/删除视图时,如何阻止用户触摸他们自己没有创建的打孔对象。

1 个答案:

答案 0 :(得分:2)

您可以使用.dispatch()方法或.process_request()中间件检查用户,也可以创建权限类以扩展您的视图。我将用第一个选项写一个简短的例子:

class PunchEdit(...):

    def dispatch(self, request, *args, **kwargs):
        # check for user logged in
        ...
        # check for user permission:
        # Take pk from kwargs
        pk = kwargs.get('pk')  # example
        # Take user from request
        user = request.user
        # check permission
        try:
            Punch.objects.get(pk=pk, user=user)
            return super(PunchEdit, self).dispatch(request, *args, **kwargs)
        except Punch.DoesNotExist, e:
            return HttpResponseForbidden()

HttpResponseForbidden()