Djangoフォームは何度もつまずきます...
ChoiceField に初期値を与えました ( Form クラスのinit )
self.fields['thread_type'] = forms.ChoiceField(choices=choices,
widget=forms.Select,
initial=thread_type)
上記のコードで作成されたフォームはthread_type
、「このフィールド(thread_type) が必要」であるため、is_valid() を渡しません。
-編集-
修正が見つかりましたが、それでもかなり当惑します。
テンプレートにコードがありました
{% if request.user.is_administrator() %}
<div class="select-post-type-div">
{{form.thread_type}}
</div>
{% endif %}
このフォームが送信されると、ユーザーが管理者でない場合、request.POST には「thread_type」がありません。
ビュー関数は、次のコードでフォームを作成します。
form = forms.MyForm(request.POST, otherVar=otherVar)
以下(上記と同じ)で初期値を与えるだけでは不十分な理由がわかりません。
self.fields['thread_type'] = forms.ChoiceField(choices=choices,
widget=forms.Select,
initial=thread_type)
また、thread_type
変数を inに含めるrequest.POST
ことで、フォームが is_valid() チェックに合格できるようになります。
フォーム クラスのコードは次のようになります。
class EditQuestionForm(PostAsSomeoneForm, PostPrivatelyForm):
title = TitleField()
tags = TagNamesField()
#some more fields.. but removed for brevity, thread_type isn't defined here
def __init__(self, *args, **kwargs):
"""populate EditQuestionForm with initial data"""
self.question = kwargs.pop('question')
self.user = kwargs.pop('user')#preserve for superclass
thread_type = kwargs.pop('thread_type', self.question.thread.thread_type)
revision = kwargs.pop('revision')
super(EditQuestionForm, self).__init__(*args, **kwargs)
#it is important to add this field dynamically
self.fields['thread_type'] = forms.ChoiceField(choices=choices, widget=forms.Select, initial=thread_type)