我有两种形式。
第一个提交到数据库。完美的工作。 第二个检索数据库信息,也可以正常工作。
但是,我在表单中有过滤效果不佳的过滤器。
我有几个过滤器。
如果设置了所有过滤器,则它们可以正常工作。
如果只设置了一个,则它们不起作用。我无法弄清楚为什么会这样。
forms.py(过滤表单):
class OvertimeForm(forms.ModelForm):
location = forms.ModelChoiceField(
queryset=Location.objects.all(),
empty_label="All Locations",
widget=forms.Select(attrs={'class': 'form-control'}))
overtime_type = forms.ModelChoiceField(
queryset=overtimeTypes.objects.all(),
empty_label='All Types',
widget=forms.Select(attrs={'class': 'form-control'}))
dateStart = forms.DateField(
widget=forms.DateInput(attrs={'class':'datepicker'}))
dateEnd = forms.DateField(
widget=forms.DateInput(attrs={'class':'datepicker'}))
class Meta:
model = Overtime
fields = ['location']
fields = ['overtime_type']
field = ['dateStart']
field = ['dateEnd']
views.py(过滤表单):
def Overtime_Results(request):
userGroup = request.user.groups.get(name__in=['Comp1' ,'Comp2' , 'Comp3' , 'Comp4'])
overtime_data = Overtime.objects.filter(client__name=userGroup)
location = None
overtime_type = None
dateStart = date.today()
dateEnd = date.today()
if request.method == 'POST':
form = OvertimeForm(data=request.POST)
if form.is_valid():
location = form.data['location']
dateStart = form.data['dateStart']
dateEnd = form.data['dateEnd']
overtime_type = form.data['overtime_type']
#This is where I think the problem is, something here isn't correct.
overtime_data = Overtime.objects.filter(location=location, overtime_type=overtime_type, overtimeDateStart__range=(dateStart, dateEnd), client__name=userGroup)
return response
else:
form = OvertimeForm()
template_name = "overtime/Overtime_Results.html"
context = {
'form': form,
'location': location,
'overtime_type': overtime_type,
'overtime_data': overtime_data,
}
return render(request, template_name, context)
在html文件中:
<div class="col-md-3">{{ form.location }}
{{ form.dateStart }} <p>To</p>
{{ form.dateEnd }}
{{ form.overtime_type }}
</div>
表单的外观如下:http://imgur.com/NFWU9ke
答案 0 :(得分:0)
您应该使用您真正关心的那些过滤器来构建查询,拆分查询集的创建,这仍然只会导致对数据库的一次调用,它更加清晰。
overtime_data = Overtime.objects.all()
location = form.cleaned_data.get('location')
if location:
overtime_data = overtime_data.filter(location=location)
# continue for other params.
您还使用form.data
代替cleaned_data
,这意味着您没有使用经过验证的数据。