如何根据用户组更改Django模板?

时间:2022-12-04 08:29:55

Right now I have two different groups of users on my site: customers and businesses.

目前,我的站点上有两组不同的用户:客户和企业。

Right now I am only using one login that allows both user groups to see their profile page.

现在我只使用一个登录,允许两个用户组查看他们的配置文件页面。

However, there are portions of the profile page I only want the Customer to see and portions I only want the business to see. How can I go about limiting what each group sees on this page?

但是,我只希望客户看到概要页面的一部分,以及我只希望业务看到的部分。我怎样才能限制每个小组在这一页上看到的内容?

Should I do it in the template with some sort of if statement? or is there some other solution anyone can let me know about?

我应该在模板中使用if语句吗?或者有没有其他的方法可以让我知道?

4 个解决方案

#1


10  

This is probably too old for you to care any more, but I stumbled here myself before figuring it out on my own. For posterity, I found the following solution:

这对你来说可能已经太老了,你再也不在乎了,但在我自己想出来之前,我在这里遇到了麻烦。为了子孙后代,我找到了以下解决方案:

In your view, add something like this:

在您看来,添加如下内容:

is_customer = request.user.groups.filter(name='Customers').exists()

In your template:
{% if is_customer %} customer stuff here {% endif %}

在您的模板中:{% if is_customer %},这里的{% endif %}

It relies on the fact that an if clause in a template will be evaluate to false for an empty list.

它依赖于这样一个事实:模板中的if子句将为空列表求值为false。

#2


13  

If you want to avoid adding anything to your view functions, and you’re using the auth context processor (django.contrib.auth.context_processors.auth) and RequestContext as per @thyagx’s answer, then you could use a template snippet like that suggested in this Google Groups post:

如果您想避免在视图函数中添加任何内容,并且您正在使用auth上下文处理器(django.悔过。authb .context_processors.auth)和RequestContext(根据@thyagx的回答),那么您可以使用一个模板片段,就像这个谷歌组帖子中建议的那样:

{% for group in user.groups.all %}
    {% if group.name == 'customers' %}
        {% comment %}Customer-specific code goes here{% endcomment %}
    {% endif %}
{% endfor %}

It’s a bit verbose, but it does mean you don’t have to do anything in your view (aside from using RequestContext), or write a custom context processor.

它有点啰嗦,但它确实意味着您不必在视图中做任何事情(除了使用RequestContext),或者编写自定义上下文处理器。

#3


12  

What I did to solve this is:

我解决这个问题的方法是

  1. I created a custom context processor which basically inserts new variables for you to use in your templates and added it to my settings. See more @ https://docs.djangoproject.com/en/1.3/ref/templates/api/#django.template.RequestContext:

    我创建了一个自定义上下文处理器,它主要是插入新的变量,以便您在模板中使用,并将其添加到我的设置中。看到更多@ https://docs.djangoproject.com/en/1.3/ref/templates/api/ django.template.RequestContext:

    TEMPLATE_CONTEXT_PROCESSORS = (
        'django.core.context_processors.debug',
        'django.core.context_processors.i18n',
        'django.core.context_processors.media',
        'django.core.context_processors.static',
        'django.contrib.auth.context_processors.auth',
        'django.contrib.messages.context_processors.messages',
        'common.user_context.user_context'
    )
    
  2. I went on to write the function user_context inside the file user_context, mine is like so:

    我继续在文件user_context中编写函数user_context,我的是这样的:

    def user_context(request):
        if request.user.is_authenticated():
            is_admin = is_local_admin(request.user)
        else:
            is_admin = False
    
        return {
            'is_local_admin': is_admin
        }
    

    is_local_admin is just a function that checks if the user belongs to the Admins group or not.

    is_local_admin是一个函数,它检查用户是否属于Admins组。

  3. Whenever I need this is_local_admin information in my template I use this to render it in my view, for example:

    每当我在模板中需要is_local_admin信息时,我就用它在视图中呈现它,例如:

    return render_to_response('create_user.html', {
        'form': form
    }, context_instance=RequestContext(request))
    

The important part is the RequestContext, which loads the custom context processor we build in step 1.

重要的部分是RequestContext,它装载我们在步骤1中构建的自定义上下文处理器。

Now in your template you can just use:

现在你可以在模板中使用:

{% if is_local_admin %}
    <h1>You can see this</h1>
{% else %}
    <h1>Nothing here</h1>
{% endif %}

Hope this helps someone. In summary: take a look at custom context processors, they are worth the read.

希望这可以帮助别人。总之:看看自定义上下文处理器,它们值得一读。

#4


7  

I implemented this through a template tag, based on what I found here. Perhaps it can be useful to someone.

我通过模板标记实现了这一点,基于我在这里发现的内容。也许它对某人有用。

In utils/utils_extras.py:

在跑龙套/ utils_extras.py:

from django import template
from django.contrib.auth.models import Group

register = template.Library()
@register.filter(name='has_group')
def has_group(user, group_name):
    try:
        group = Group.objects.get(name=group_name)
    except:
        return False  # group doesn't exist, so for sure the user isn't part of the group

    # for superuser or staff, always return True
    if user.is_superuser or user.is_staff:
        return True

    return user.groups.filter(name=group_name).exists()

Then in the template itself:

然后在模板本身:

{% load utils_extras %}
{% if user|has_group:"mygroup" %}

#1


10  

This is probably too old for you to care any more, but I stumbled here myself before figuring it out on my own. For posterity, I found the following solution:

这对你来说可能已经太老了,你再也不在乎了,但在我自己想出来之前,我在这里遇到了麻烦。为了子孙后代,我找到了以下解决方案:

In your view, add something like this:

在您看来,添加如下内容:

is_customer = request.user.groups.filter(name='Customers').exists()

In your template:
{% if is_customer %} customer stuff here {% endif %}

在您的模板中:{% if is_customer %},这里的{% endif %}

It relies on the fact that an if clause in a template will be evaluate to false for an empty list.

它依赖于这样一个事实:模板中的if子句将为空列表求值为false。

#2


13  

If you want to avoid adding anything to your view functions, and you’re using the auth context processor (django.contrib.auth.context_processors.auth) and RequestContext as per @thyagx’s answer, then you could use a template snippet like that suggested in this Google Groups post:

如果您想避免在视图函数中添加任何内容,并且您正在使用auth上下文处理器(django.悔过。authb .context_processors.auth)和RequestContext(根据@thyagx的回答),那么您可以使用一个模板片段,就像这个谷歌组帖子中建议的那样:

{% for group in user.groups.all %}
    {% if group.name == 'customers' %}
        {% comment %}Customer-specific code goes here{% endcomment %}
    {% endif %}
{% endfor %}

It’s a bit verbose, but it does mean you don’t have to do anything in your view (aside from using RequestContext), or write a custom context processor.

它有点啰嗦,但它确实意味着您不必在视图中做任何事情(除了使用RequestContext),或者编写自定义上下文处理器。

#3


12  

What I did to solve this is:

我解决这个问题的方法是

  1. I created a custom context processor which basically inserts new variables for you to use in your templates and added it to my settings. See more @ https://docs.djangoproject.com/en/1.3/ref/templates/api/#django.template.RequestContext:

    我创建了一个自定义上下文处理器,它主要是插入新的变量,以便您在模板中使用,并将其添加到我的设置中。看到更多@ https://docs.djangoproject.com/en/1.3/ref/templates/api/ django.template.RequestContext:

    TEMPLATE_CONTEXT_PROCESSORS = (
        'django.core.context_processors.debug',
        'django.core.context_processors.i18n',
        'django.core.context_processors.media',
        'django.core.context_processors.static',
        'django.contrib.auth.context_processors.auth',
        'django.contrib.messages.context_processors.messages',
        'common.user_context.user_context'
    )
    
  2. I went on to write the function user_context inside the file user_context, mine is like so:

    我继续在文件user_context中编写函数user_context,我的是这样的:

    def user_context(request):
        if request.user.is_authenticated():
            is_admin = is_local_admin(request.user)
        else:
            is_admin = False
    
        return {
            'is_local_admin': is_admin
        }
    

    is_local_admin is just a function that checks if the user belongs to the Admins group or not.

    is_local_admin是一个函数,它检查用户是否属于Admins组。

  3. Whenever I need this is_local_admin information in my template I use this to render it in my view, for example:

    每当我在模板中需要is_local_admin信息时,我就用它在视图中呈现它,例如:

    return render_to_response('create_user.html', {
        'form': form
    }, context_instance=RequestContext(request))
    

The important part is the RequestContext, which loads the custom context processor we build in step 1.

重要的部分是RequestContext,它装载我们在步骤1中构建的自定义上下文处理器。

Now in your template you can just use:

现在你可以在模板中使用:

{% if is_local_admin %}
    <h1>You can see this</h1>
{% else %}
    <h1>Nothing here</h1>
{% endif %}

Hope this helps someone. In summary: take a look at custom context processors, they are worth the read.

希望这可以帮助别人。总之:看看自定义上下文处理器,它们值得一读。

#4


7  

I implemented this through a template tag, based on what I found here. Perhaps it can be useful to someone.

我通过模板标记实现了这一点,基于我在这里发现的内容。也许它对某人有用。

In utils/utils_extras.py:

在跑龙套/ utils_extras.py:

from django import template
from django.contrib.auth.models import Group

register = template.Library()
@register.filter(name='has_group')
def has_group(user, group_name):
    try:
        group = Group.objects.get(name=group_name)
    except:
        return False  # group doesn't exist, so for sure the user isn't part of the group

    # for superuser or staff, always return True
    if user.is_superuser or user.is_staff:
        return True

    return user.groups.filter(name=group_name).exists()

Then in the template itself:

然后在模板本身:

{% load utils_extras %}
{% if user|has_group:"mygroup" %}