Django:自定义表单__init __()和ReverseMatch错误

时间:2014-12-09 21:44:03

标签: django forms views

我有像这样的自定义表单代码

class ReportForm(forms.Form):
start = forms.DateField(forms.DateInput())
end = forms.DateField(forms.DateInput())
type = forms.CharField(max_length=2, choices=ACTIVITY_CHOICES, default=RUNNING)

def clean(self):
    if 'start' in self.cleaned_data > 'end' in self.cleaned_data:
        raise forms.ValidationError("Popraw daty")
    else:
        pass

问题是,当我尝试使用该表单加载页面时,我得到TypeError at /reportform __init__() got an unexpected keyword argument 'default'

这与type = forms.CharField的选项相关联 - 但是当我删除它们时,我得到了

NoReverseMatch at /reportform
Reverse for '' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

这是我的观点,试图使用这种形式:

def ReportRequest(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/')
    if request.method == 'POST':
        form = ReportForm(request.POST)
        if form.is_valid():
            usrname = request.user
            q = Training.objects.filter(user__in==usrname)
            q = Training.objects.filter(date__in>=form.cleaned_data['start'])
            q = Training.objects.filter(date__in<=form.cleaned_data['end'])
            q = Training.objects.filter(type__in==form.cleaned_data['type'])
            if q.count() == 0:
                return HttpResponseRedirect('/notrainings/')
            avg_length = q.aggregate(Avg('length'))
            avg_distance = q.aggregate(Avg('distance'))
            avg_calories = q.aggregate(Avg('caloriesBurnt'))
            return HttpResponseRedirect('/report/')
        else:
            return render_to_response('reportform.html', {'form':form}, context_instance=RequestContext(request))
    else:
        form = ReportForm()
        return render_to_response('reportform.html',{'form':form}, context_instance = RequestContext(request))

我不知道如何处理这个,我非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

defaultModel CharField的有效参数。

对于表单字段,有效参数为initial

尝试:

type = forms.CharField(max_length=2, choices=ACTIVITY_CHOICES, initial=RUNNING) #initial instead of default

initial here

上的文档

现在你的反向比赛是一个完全不同的问题。 (Woudl建议深入挖掘它,如果你仍然卡住,就会创建一个新问题 - 暗示:URL没有解决任何问题。)