Django: UpdateView restrict per user
Asked Answered
Q

2

8

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

Query answered 21/12, 2011 at 18:45 Comment(0)
H
11

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)
Hegira answered 21/12, 2011 at 20:14 Comment(1)
I get Page not found (404) if it's not the user. I want another error saying Not Allowed for this user.Cabby
S
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

Sublease answered 21/12, 2011 at 19:39 Comment(1)

© 2022 - 2024 — McMap. All rights reserved.