chr*_*ris 11 django django-templates django-views
现在我的网站上有两组不同的用户:客户和企业.
现在我只使用一个登录,允许两个用户组查看他们的个人资料页面.
但是,我只希望客户看到配置文件页面的某些部分,而我只希望业务部门看到这些部分.如何限制每个群组在此页面上看到的内容?
我应该在模板中使用某种if语句吗?还是有其他任何人可以让我知道的解决方案?
Pau*_*ite 13
如果您想避免向视图函数添加任何内容,并且您正在使用身份验证上下文处理器(django.contrib.auth.context_processors.auth)并RequestContext根据@ thyagx的答案,那么您可以使用此Google网上论坛帖子中建议的模板代码段:
{% for group in user.groups.all %}
    {% if group.name == 'customers' %}
        {% comment %}Customer-specific code goes here{% endcomment %}
    {% endif %}
{% endfor %}
它有点冗长,但它确实意味着您不必在视图中执行任何操作(除了使用RequestContext),或编写自定义上下文处理器.
jor*_*lli 12
这可能太老了,你不能再关心了,但我自己偶然发现了自己.对于后代,我找到了以下解决方案:
在您的视图中,添加以下内容:
is_customer = request.user.groups.filter(name='Customers').exists()
在您的模板中:
{% if is_customer %} customer stuff here {% endif %}
它依赖于以下事实:if对于空列表,模板中的子句将被评估为false.
thy*_*agx 12
我做的是解决这个问题:
我创建了一个自定义上下文处理器,它基本上插入了新的变量供您在模板中使用并将其添加到我的设置中.查看更多@ 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'
)
我继续写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 只是一个检查用户是否属于Admins组的函数.
每当我is_local_admin在模板中需要这些信息时,我就会在我的视图中使用它来渲染它,例如:
return render_to_response('create_user.html', {
    'form': form
}, context_instance=RequestContext(request))
重要的部分是RequestContext,它加载我们在步骤1中构建的自定义上下文处理器.
现在在您的模板中,您可以使用:
{% if is_local_admin %}
    <h1>You can see this</h1>
{% else %}
    <h1>Nothing here</h1>
{% endif %}
希望这有助于某人.总结:看看自定义上下文处理器,它们值得一读.
我是根据我在这里找到的内容通过模板标签实现的.也许它对某人有用.
在utils/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()
然后在模板本身:
{% load utils_extras %}
{% if user|has_group:"mygroup" %}