Получите группу пользователей в шаблоне

Я считаю, что «Давайте перепишем прошлое и попытаемся исправить эту ошибку, притворяясь, что ничего не работало» является ценной отладочной мантрой в безвыходных ситуациях:

https://stackoverflow.com/questions / 978904 / сделайте вас потребительной-Оруэлл пришедшего переписывания-отладка-филосовскую закрыта

15
задан Mirko Brombin 10 March 2016 в 07:43
поделиться

1 ответ

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.

28
ответ дан 1 December 2019 в 00:37
поделиться
Другие вопросы по тегам:

Похожие вопросы: