Django: UpdateView restrict per user

喜欢而已 提交于 2019-12-10 13:27:20

问题


I have a site where users can create and edit their own lists.

I'm using the generic view CreateView to allow users to create lists.

I would like to use the generic view UpdateView to allow them to edit the lists, but the login_required=True is not enough in this case, since only the list creator can edit his/her list.

2 questions:

1) is there any parameter that I can specify in the URLconf to add this restrictions?

2) can I impose the those generic views should only work with POST and not GET?

Thanks


回答1:


You could override get_queryset on the UpdateView:

def get_queryset(self):
    base_qs = super(YourListUpdateView, self).get_queryset()
    return base_qs.filter(user=self.request.user)



回答2:


1) you can write decorator and use it same way as login_required decorator, ie:

def user_permitted(function):
    def decorator(function):
        def _wrapped_view(request, *args, **kwargs):
            # get obj from request
            if obj.user != request.user:
                return HttpResponseRedirect(reverse('forbidden'))
            return function(request, *args, **kwargs)
        return _wrapped_view
    return decorator(function)

2) yes, see decorators and Decorating class-based views



来源:https://stackoverflow.com/questions/8594759/django-updateview-restrict-per-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!