Question

I am new to django/python and working my way through my webapp. I need assistance in solving one of my problems.

In my app, I am planning to assign each user (from auth_user) to one of the group ( from auth_group). Each group can have multiple users. I have entry in auth_group, auth_user and auth_user_groups. Here is my question:

  1. At time of login I want to check that logging user belongs to which group?

  2. I want to keep that group info in session/cache so all pages I can show information about that group only.

If you have any sample code will be great.

Was it helpful?

Solution

Giving support to the very well @trinchet's answer with an example of context_processor code.

Puts inside your webapp a new file called context_processors.py and writes this lines on it:

def user_groups(request):
"""
Add `groups` var to the context with all the
groups the logged in user has, so you can access 
in your templates to this var as: {{ groups }}
"""
groups = None
if request.user.is_authenticated():
    groups = user.groups
return {'groups': groups}

Finally on your settings.py add 'webbapp.context_processors.user_groups'to TEMPLATE_CONTEXT_PROCESSOR:

 TEMPLATE_CONTEXT_PROCESSORS = (
    'webbapp.context_processors.user_groups', 
)

OTHER TIPS

1) Be user an instance of auth.models.User, you can get all groups the user belong to, through user.groups. If you want to ask at time of login then you should do this in your login view.

2) You can use session or cache approaches to deal with, this is irrelevant, but once you have the group you need to render the pages having this value, i mean, you need to provide the group to the template rendering, to do this I suggest to you using a custom context processor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top