开发者

Overriding save() model method for permissions

Am trying to override save() method so that only the creator and administrator are able to update the model field values as :

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)

While update am passing request to the save method as

 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开发者_JAVA百科')
    else:
    form_shastra_edit = ShastraEditForm(instance = shastra)

But am getting " tuple index out of range " error . What is going wrong in this ?


You can not use request in a Model.save() method. You have to do request-based validation in your views method (in your edit method for instance). The Model layer is unaware of 'request' objects..

Make your edit method something like:

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜