【问题标题】:Every value in request.POST is a listrequest.POST 中的每个值都是一个列表
【发布时间】:2012-06-12 15:12:33
【问题描述】:

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

【问题讨论】:

  • 你显然在这里做了一些奇怪的事情。您根本不应该访问 request.POST 值。请至少发布验证功能。

标签: python django forms


【解决方案1】:

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 获取的。那么为什么不只使用表单来处理所有字段呢?如果在表格中做起来有困难或者有什么特殊的逻辑考虑,可以在问题中说清楚。

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2023-01-29
      • 2017-01-12
      • 2018-04-04
      • 1970-01-01
      • 2021-05-19
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 2019-02-17
      相关资源
      最近更新 更多