覆盖权限的save()模型方法

时间:2011-07-04 11:08:35

标签: django methods model save override

尝试覆盖save()方法,以便只有创建者和管理员能够将模型字段值更新为:

if not self.pk:
        super(Shastra, self).save(*args, **kwargs)
else:
        if (self.person == args[0].user) or (self.person.is_superuser):
            super(Shastra, self).save(*args, **kwargs)

更新时将请求传递给save方法

 def edit(request, shastra_id):
    shastra_id = int(shastra_id)
    shastra = Shastra.objects.get(pk = shastra_id )
    if request.method == 'POST':
        form_shastra_edit = ShastraEditForm(request.POST, instance = shastra)
        if form_shastra_edit.is_valid():
            form_shastra_edit.save(request)
            return HttpResponseRedirect('/edited/successfully')
    else:
    form_shastra_edit = ShastraEditForm(instance = shastra)

但是我的“元组索引超出范围”错误。这有什么问题?

1 个答案:

答案 0 :(得分:1)

您不能在Model.save()方法中使用请求。您必须在视图方法中进行基于请求的验证(例如,在您的编辑方法中)。 Model层不知道'request'对象..

使您的编辑方法类似于:

def edit(request, shastra_id):
    shastra_id = int(shastra_id)
    shastra = Shastra.objects.get(pk = shastra_id )
    if request.method == 'POST':
        form_shastra_edit = ShastraEditForm(request.POST, instance = shastra)
        if form_shastra_edit.is_valid() and shastra.user == request.user:
                form_shastra_edit.save(request)
                return HttpResponseRedirect('/edited/successfully')
    else:
        form_shastra_edit = ShastraEditForm(instance = shastra)