request.POST中的每个值都是一个列表

时间:2012-06-12 15:12:33

标签: python django forms

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

2 个答案:

答案 0 :(得分:3)

request.POSTQueryDict, which is dictionary-like class but not dictionary

你可以尝试

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获取。那为什么不仅仅使用表单来处理所有字段?如果您在表单中遇到问题或者有任何特殊的逻辑考虑,您可以在问题中明确说明。

答案 1 :(得分:0)

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

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

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