django从表单到视图传递参数

时间:2014-06-02 20:12:12

标签: python django

我有一个接受单个日期或日期范围的表单。然后将日期传递给查询DB并生成结果的后续视图。我已设法通过URL传递单个日期  但我还没有找到一种方法将日期范围从表单传递到运行查询的后续视图。 (注意:我理解下面提供的表单的缩进是关闭的。对于某些人来说这是我的第一篇文章,而且我对于堆栈溢出的所有细微之处还不是很明智)

class Date_rangeFRM(forms.Form):
Single_date = forms.DateField(required=False)
Date_start = forms.DateField(required=False)
Date_end = forms.DateField(required=False) 



def date_range(request):
context = RequestContext(request)

if request.method == 'POST':
    form = Date_rangeFRM(request.POST)
    print "valid", form.is_valid()
    print "form", str(form)
    if form.is_valid():
            #print "form", str(form)
        Single_date = form.cleaned_data['Single_date']
        Date_start = form.cleaned_data['Date_start']
        Date_end = form.cleaned_data['Date_end']


        if Single_date != "":
            #print "redirecting to Dav View:", '/counter/%02d-%02d-%02d/Day_view/' %(Single_date.year,Single_date.month,Single_date.day)
            return HttpResponseRedirect('/counter/%02d-%02d-%02d/Day_view/' %(Single_date.year,Single_date.month,Single_date.day))



        else:
            #****passing Magic ********

            return HttpResponseRedirect('/counter/History_View/')
    else: 
        print form.errors

else:
    form = Date_rangeFRM()

return render_to_response('counter/historyFRM.html', {'form':form}, context)





def History_View(request):
context = RequestContext(request)

    #****** Receiving magic******** 

date_start = form.cleaned_data['date_start']
date_end = form.cleaned_data['date_end']
context['meal_list'] = meal_list
context['comp_list'] = comp_list
context['day_list']  = day_list             

dt_range = []  

day_list = RecordedDays.objects.filter(profile= request.user.userprofile, 
Date__gte = date_start, Date__lte = date_end     )

for day in day_list:
    dt_range.append(day.Date)

    meal_list = MealType.objects.filter(
    newDay__profile = request.user.userprofile, 
    newDay__Date__gte = date_start, newDay__Date__lte = date_end     )
                #newDay__Date= date( int(year),  int(month), int(day) ) )
    for meal in meal_list:
        dt_range.append([ meal.get_mealNum_display(), meal.Mealtotal()  ])
        comp_list =Ingredient.objects.filter(numMeal = meal)


        for comp in comp_list:
            dt_range[-1].append([comp.component, comp.comp_total()] )  




return render_to_response('counter/history_view.html', context

此外,我并不完全确定我正确使用了__lte,__ gte功能。如果可以的话请检查一下。非常感激。 谢谢你的帮助。

0 个答案:

没有答案