1

我遇到了问题,因为 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() 但我不能将它附加到字典中。谢谢大家的帮助。

4

2 回答 2

3

request.POST是一个QueryDict,它是类字典类但不是字典

你可以试试

form_data = request.POST.copy()
form_data.update({'hours': hours})

#instead of
form_data = {'hours': hours}
form_data.update(request.POST.copy())

但是,根据您的代码,hours也是从中获取的request.POST。那么为什么不只使用表单来处理所有字段呢?如果你在表格中做起来有困难或者有任何特殊的逻辑考虑,你可以在问题中说清楚。

于 2012-06-12T16:25:07.323 回答
0

您应该按如下方式实例化表单:

form = MyForm(request.POST)
if form.is_valid():
    pass

在 Django 中获得基本的表单验证不需要其他代码。如果您需要添加值,request.POST则考虑创建隐藏的输入字段并在表单中包含预期的值。

于 2012-06-12T17:20:10.803 回答