I have a page in my Django app that needs to do one of the following depending on the status of the logged in user in relation to a group (not a Django user group; something custom to my app) represented on the page:
- If the user can join the group, display a link to join the group.
- If the user is in the group, display a link to leave the group.
- If the user can’t join the group, don’t display either link.
One way of doing this would be to create three templates (one with the join link, one with the leave link, and one with no link) and choose the appropriate one in the view. I feel like it may be overkill to have three different templates that will only differ in one line of code, so I have not gone that route as of yet.
Displaying the correct content for conditions 1 and 2 exclusively using a template is not possible, and if it were I do not think it would be advisable. Users to groups is a many-to-many relationship, and determining group membership requires passing a user to the group or passing a group to the user.
Since Django templates don’t allow passing function arguments, I am trying to solve this by passing a context variable to the template using get_context_data.
def get_context_data(self, **kwargs):
context = super(NetworkDetails, self).get_context_data(**kwargs)
user = ???
context['in_group'] = user.in_group(context['group_detail'])
return context
If I do that, how can I get the currently logged in user within that method? If that isn’t possible, where else can I get that information outside of the template? Is there an accepted method of doing something like this?
Thanks!
That’s funny because if you can choose what template to include, you can just choose what html to display. Instead of:
You could just have:
So, I don’t understand why you want to use template inclusion.