Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can access <code>self</code> inside the method decorator, so you <em>do</em> have access to the current object calling <code>self.get_object()</code>.</p> <p>Anyway, if you are only using this behavior on generic views, you're probably better off creating a mixin that implement the <code>dispatch</code> method (or could be the <code>get_object</code> method) and does the check there, for example (using a little of imagination since idk how your groups are defined, maybe you are using django.contrib.auth groups): </p> <pre><code>class GroupRestrictionMixin(object): group_field = 'group' def dispatch(request, *args, **kwargs): self.request = request self.args = args self.kwargs = kwargs obj_group = getattr(self.get_object(), self.group_field) user_groups = request.user.groups if obj_group not in user_groups: raise PermissionDenied return super(GroupRestrictionMixin, self).dispatch(request, *args, **kwargs) </code></pre> <p>Then you can create any view that needs that behavior using your mixin: </p> <pre><code>class SecretPostView(GroupRestrictionMixin, DetailView): pass </code></pre> <p>Idk if it's what you would call "idiomatic", but that's the easier way that comes to mind to keep it simple and reusable.</p> <p><strong>EDIT:</strong> the request, args and kwargs must be setted here so the <code>get_object</code> method haves access to them. It gets a little uglier (you gotta repeat some code that's on the base <code>dispatch</code> method), but still works :F</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload