[Answer]-Display django class based views data depending on user permissions?

1👍

If I were you, I’d do this in a template:

{% if user == post.author %}
    display edit button
{% else %}
    display view button or something else
{% endif %}

One more variant (if you want to do all the logic in a view) is to create a mixin:

class CanEditMixin(object):
    def get_context_data(self, **kwargs):
        """
        The method populates Context with can_edit var
        """
        # Call the base implementation first to get a context
        context = super(CanEditMixin, self).get_context_data(**kwargs)
        #Update Context with the can_edit
        #Your logic goes here (something like that)
        if self.request.user == self.get_object().author
            context['can_edit']=True
        else:
            context['can_edit']=False
        return context

Then you will need to update your view (the order matters):

class PostDetailView(CanEditMixin, LoginRequiredMixin, DetailView):
    #your view

and your template:

{% if can_edit %}
    display edit button
{% else %}
    display view button or something else
{% endif %}    

Also depending on specifics of your problem you may be interested in django object-level permission packages. These packages allow you to add permission for the user to edit a given object. In that case you can just write in your template something like that:

{% if perms.post.can_edit %}
    display edit button
{% else %}
    display view button or something else
{% endif %}   

a link to the django docs.

Leave a comment