request.POSTのすべての値がリスト内にあるため、問題が発生しています。だから私がこれをするときはいつでも:
MyForm(request.POST)
リストではなく文字列を期待しているため、どの検証も合格しません。そして、エラーメッセージはこの種のものです:
[u'13/04/2000'] is not a valid date
request.POSTをフォームに渡すだけの設定や変更が必要なものはありますか?私は本当にすべてのフィールドに対してrequest.POST.get(..)のようなことをしたくありません。
これが私のフォームです。
class FormAddCourse(forms.Form):
career = choice_field(Career)
assignature = choice_field(Assignature)
start_date = forms.DateField(label = spanish('col_name', 'start_date', True),
help_text = "Formato: dd/mm/aaaa")
end_date = forms.DateField(label = spanish('col_name', 'end_date', True),
help_text = "Formato: dd/mm/aaaa")
day_choices = [('Mo', 'Lunes'), ('Tu', 'Martes'), ('We', 'Miércoles'), ('Th', 'Jueves'),
('Fr', 'Viernes'), ('Sa', 'Sábado'), ('Su', 'Domingo')]
days = forms.MultipleChoiceField(label = spanish('col_name_plural', 'day', True),
widget = CheckboxSelectMultiple,
choices = day_choices)
length_choices = (
('S', spanish('choices', 'semesterly', True)),
('Y', spanish('choices', 'yearly', True)),
)
length = forms.ChoiceField(label = spanish('col_name', 'length', True),
widget = RadioSelect,
choices = length_choices)
hours = forms.CharField(widget = HiddenInput,
max_length = 300,
validators=[validate_hours])
そして、これが私の見解です:
def add_course_view(request):
if request.method == "GET":
form = FormAddCourse()
c = {'form': form}
return render_to_response('crud/courses/add.html', c, RequestContext(request))
elif request.method == "POST":
try:
hours = get_hours(request.POST)
form_data = {'hours': hours}
form_data.update(request.POST.copy())
form = FormAddCourse(form_data)
if form.is_valid(): # This thing never passes
career = form.cleaned_data['career']
assignature = form.cleaned_data['assignature']
start_date = form.cleaned_data['start_date']
end_date = form.cleaned_data['end_date']
days = form.cleaned_data['days']
length = form.cleaned_data['length']
hours = form.cleaned_data['hours']
credits = calculate_credits(valid_hours)
# alter database
# course = Course.objects.create(career=career, assignature=assignature, start_date=start_date, end_date=end_date, days=days, length=length, credits=credits, hours=hours)
if u'submit_another' in request.POST:
# Submit and add another
messages.add_message(request, messages.SUCCESS, u"El curso ha sido guardado. Agregue otro.")
return redirect('crud.views.add_course_view')
else:
# Submit and end
messages.add_message(request, messages.SUCCESS, u"El curso ha sido guardado.")
return redirect('ssys.views.homepage')
except FieldError as e:
# return user to complete form with fields already filled
pass
検証関数に関しては、唯一のカスタム関数はvalidate_hoursです。これは、form_dataに手動で時間を追加するため、実際に通過する唯一の関数です。
問題が何であるかを理解しました。request.POST.copy()に追加できますが、辞書に追加できません。よろしくお願いします。