使用对象。获取或者对象.过滤器获取要在表格fi中使用的特定组

2024-05-20 15:11:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个表单,由于隔离要求,需要我阻止某些用户看到某些结果。你知道吗

表单工作得很好,但是我想应用一个过滤器,它查看user的组,并根据用户所属的组过滤表单内容。你知道吗

你知道吗视图.py使用过滤器呈现窗体。你知道吗

def Overtime_Results(request):
employeeGroup = request.user.groups.get(name='Client1' or 'Client2' or 'Client3' or 'Client4')
overtime_data = Overtime.objects.filter(client=employeeGroup)
location = None
if request.method == 'POST':
    form = OvertimeForm(data=request.POST)
    if form.is_valid():
        location = form.data['location']
        overtimeid = Location.objects.all()
        overtime_data = Overtime.objects.filter(location=location, client=employeeGroup)
else:
    form = OvertimeForm()

template_name = "overtime/Overtime_Results.html"
context = {
    'form': form,
    'location': location, 
    'overtime_data': overtime_data,
}
return render(request, template_name, context)

这是检查用户是否属于某个组的筛选器。你知道吗

employeeGroup = request.user.groups.get(name='Client1' or 'Client2' or 'Client3' or 'Client4')

我本质上希望它返回用户所属的组,这将随后应用于表单过滤器。你知道吗

我尝试了两种过滤方法,用多种方法获取。上述方法有效,但仅适用于Client1。Client2和随后的客户机不工作。你知道吗

Edit:我想我需要在SQL中使用与“in”语句等价的语句。但是,我好像不知道怎么做。你知道吗

我现在收到的错误是:

    Group matching query does not exist.

如果用户分配了与查询结果匹配的有效组,则访问该页时。你知道吗


Tags: or用户nameform过滤器表单datarequest
2条回答

这个QuerySet API Field Lookups using "in"怎么样。你知道吗

 request.user.groups.get(name__in=['Client1' ,'Client2' , 'Client3' , 'Client4'])

您的问题归结为:

request.user.groups.get(name='Client1')

这是因为:

'Client1' or 'Client2' or 'Client3' or 'Client4'

总是'Client1'。你知道吗

如果只想获取当前用户所属的所有组:

user_groups = request.user.group_set.all()

如果您的用户只能属于一个组,请使用:

user_group = request.user.group

相关问题 更多 >