gpt4 book ai didi

python - 无法获取属于当前用户的组

转载 作者:行者123 更新时间:2023-12-01 02:22:28 24 4
gpt4 key购买 nike

我正在构建一个 Django 应用程序,需要两件事。首先,它需要用户有权访问的一组组。对于这组组,我的模板应该为每个组创建一个按钮。接下来,它需要与先前找到的组集中的组多对多相关的一组“属性”对象(这就是说,我需要分配给用户有权访问的组的每个属性)。对于每个属性,都会创建一个按钮。我现在正在本地主机上与管理员用户一起构建此元素,并且我创建了一个具有测试属性的测试组,并将管理员用户分配给该组。然而,Django 似乎没有检测到这一点。相关代码如下:

View .py

from __future__ import unicode_literals
from django.shortcuts import render
from UsageData.models import Property, User, Group, MeterData
from django.contrib import auth

def reports_proerty_list(request):

if request.user.is_authenticated():

current_user_groups = Group.objects.filter(id__in=request.user.groups.all())
current_user_properties = Property.objects.filter(groups__in=current_user_groups)

return render(request, 'App/App-Template-Page.html')

else:

# The user is redirected to the sign-in page

应用程序模板页面.html

        <div class="row">

{% if current_user_groups %}
{% for group in current_user_groups %}
<div class="col-sm-2 col-md-2 col-lg-2 text-center">
<button class="tab-selector inactive" id="{{ group.id }}">{{ group.name }}</button>
</div>
{% endfor %}
{% else %}
<div class="col-sm-2 col-md-2 col-lg-2 text-center">
<button class="tab-selector inactive" id="{{ group.id }}">Group 1</button>
</div>
<div class="col-sm-2 col-md-2 col-lg-2 text-center">
<button class="tab-selector inactive" id="{{ group.id }}">Group 2</button>
</div>
<div class="col-sm-2 col-md-2 col-lg-2 text-center">
<button class="tab-selector inactive" id="{{ group.id }}">Group 3</button>
</div>
<div class="col-sm-2 col-md-2 col-lg-2 text-center">
<button class="tab-selector inactive" id="{{ group.id }}">Group 4</button>
</div>
<div class="col-sm-2 col-md-2 col-lg-2 text-center">
<button class="tab-selector inactive" id="{{ group.id }}">Group 5</button>
</div>
<div class="col-sm-2 col-md-2 col-lg-2 text-center">
<button class="tab-selector inactive" id="{{ group.id }}">Group 6</button>
</div>
{% endif %}
</div>

我遇到的问题是,页面加载时会显示模板的 {% else %} 部分,我认为这意味着 current_user_groups 不存在。有人知道为什么会发生这种情况吗?如果不先进行此操作,我自然无法继续处理 Property 对象。谢谢!

最佳答案

您尚未将任何变量传递到 render 的上下文中功能

  return render(request, 'App/App-Template-Page.html',{
'current_user_groups': current_user_groups,
'current_user_properties': current_user_properties
})

这条线也可以简化

current_user_groups = Group.objects.filter(id__in=request.user.groups.all())

current_user_groups = request.user.groups.all()

关于python - 无法获取属于当前用户的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47820431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com