Reputation: 12378
I have data that can be viewed in multiple ways. The different ways depend on whether the user is logged in/anonymous, and if the user is logged in, it depends on whether the user is the author/reader of the post.
I have been looking through django class based views and django braces and I haven't found an established answer to dealing with this. I'm assuming this sort of decision making will result in a tree structure and so far, the code I've seen directs the user to a url depending on the user's permissions, it doesn't display different types of data depending on the user's permissions/login status.
What's the best approach to dealing with this? Or is there code that I've missed or haven't seen that handles this?
Note: I'd like to use django class based views.
For example:
I visit a stackoverflow post.
Display post and comments.
If anonymous user, display join stackoverflow data elements.
If logged in user, check if author or not author.
If author, display edit post data elements.
If not author, do not display edit post data elements.
How do I represent the above conditional statements in a django CBV correctly?
Upvotes: 0
Views: 1947
Reputation: 590
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.
Upvotes: 1