I want to display a menu that changes according to the user group of the currently logged in user, with this logic being inside of my view, and then set a variable to check in the template to determine which menu items to show....I'd asked this question before, but my logic was being done in the template. So now I want it in my view...The menu looks as below
<ul class="sidemenu">
<li><a href="/">General List </a></li>
<li><a href="/sales_list">Sales List </a></li>
<li><a href="/add_vehicle">Add a New Record </a></li>
<li><a href="/edit_vehicle">Edit Existing Record </a></li>
<li><a href="/filter">Filter Records </a></li>
<li><a href="/logout">Logout </a></li>
</ul>
Suppossing the user is management, they'll see everything...But assuming the user is in the group sales, they'll only see the first two and the last two items...and so on. I also want a dynamic redirect after login based on the user's group. Any ideas?
The standard Django way of checking permissions is by the individual permission flags rather than testing for the group name.
If you must check group names, being aware that Users to Groups is a many-to-many relationship, you can get the first group in the list of groups in your template with something like this:
{{ user.groups.all.0 }}
or using it like this in a conditional (untested but should work):
{% ifequal user.groups.all.0 'Sales' %}
...
{% endif %}
If you go with the preferred permission model you would do something like the following.
...
{% if perms.vehicle.can_add_vehicle %}
<li><a href="/add_vehicle">Add a New Record </a></li>
{% endif %}
{% if perms.vehicle.can_change_vehicle %}
<li><a href="/edit_vehicle">Edit Existing Record </a></li>
{% endif %}
...
These are the permissions automatically created for you by syncdb
assuming your app is called vehicle
and the model is called Vehicle
.
If the user is a superuser they automatically have all permissions.
If the user is in a Sales group they won't have those vehicle permissions (unless you've added those to the group of course).
If the user is in a Management group they can have those permissions, but you need to add them to the group in the Django admin site.
For your other question, redirect on login based on user group: Users to Groups is a many-to-many relationship so it's not really a good idea to use it like a one-to-many.