Django的形式出遊我......給予初始值提高了在Django「需要的字段值」的錯誤很多次
我給初值爲ChoiceField(Form類的初始化)
self.fields['thread_type'] = forms.ChoiceField(choices=choices,
widget=forms.Select,
initial=thread_type)
使用上述代碼與thread_type
一起創建的表單不會傳遞is_valid(),因爲'此字段(thread_type)是必需的'。
-EDIT-
找到了修復程序,但它仍然讓我困惑不已。
我在模板
{% 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)
而且,包括在request.POST
的thread_type
變量允許形式傳遞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)
你能展示更多代碼嗎?你什麼時候運行這條線? – YardenST
謝謝。用相關的代碼更新了這個問題。 – eugene