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辞書のようなクラスですが、辞書ではありません

あなたは試すことができます

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 に答える