Django UpdateView中的对象所有权验证 [英] Object ownership validation in Django UpdateView

查看:79
本文介绍了Django UpdateView中的对象所有权验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:

对我来说更好的解决方案是使用权限系统,特别是因为我需要其他类型的对对象的受控访问。我现在使用Django-guardian来帮助获得这样的对象级权限。

The better solution for me was just using a permissions system, especially since I needed other types of controlled access to objects. I now use Django-guardian to help with object level permissions like this.

原文:

我在django标准书上做了一些扩充通过让用户上载故事以及让作者,发布者等来指导用户。我试图仅让故事的作者(创作者)使用updateview,而其他用户则被重定向。

I'm expanding a bit on the standard django book guide by letting users upload stories, as well as having author, publisher, etc. I'm attempting to only let authors (creators) of a story use the updateview, with other users being redirected away.

在UpdateStory视图中修改get_object将其设置为关闭,但由于某种原因,追溯通过我的StoryForm init 。错误是'HttpResponseRedirect'对象没有属性'_meta'

Modifying get_object in the UpdateStory view set it off, but the traceback goes through my StoryForm init for some reason. The error is 'HttpResponseRedirect' object has no attribute '_meta'

views.py

class UpdateStory(LoginRequiredMixin, UpdateView):
    model = Story
    template_name = 'stories/story_update.html'
    form_class = StoryForm

    def get_object(self, queryset=None):
        obj = super(UpdateStory, self).get_object()
        if not obj.author == self.request.user:
            return redirect(obj)
        return obj

形式。 py

class StoryForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(StoryForm,self).__init__(*args, **kwargs)

I仍然很新,所以可能很明显,但是我已经找了几个小时,却很沮丧。

I'm still new, so it might be obvious, but I've been looking for a couple hours and I'm stumped.

推荐答案

http://ccbv.co.uk/projects/Django/1.5/django.views.generic.edit/UpdateView/

通过上面的链接了解 UpdateView 的工作方式。 get_object 应该返回模型实例,而不应该返回 HttpResponseRedirect 对象,这就是为什么要获取该对象错误。

Go through the above link to understand how UpdateView works. get_object is supposed to return the model instance, It is not supposed to return HttpResponseRedirect object, that's why you are getting that error.

尝试执行如下所示的 dispatch 方法签入。

Try doing the check in dispatch method like the following.

def dispatch(self, request, *args, **kwargs):
    """ Making sure that only authors can update stories """
    obj = self.get_object()
    if obj.author != self.request.user:
        return redirect(obj)
    return super(UpdateStory, self).dispatch(request, *args, **kwargs)




PS:我想不是建议覆盖调度。但是,由于
必须同时检查get和post方法,因此覆盖调度
会更容易。

PS: I guess it is not recommended to override dispatch. But as you have to do the check on both get and post methods, overriding dispatch will be easier.

这篇关于Django UpdateView中的对象所有权验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆