2013-08-20 12 views
2

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.POSTthread_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) 
+2

你能展示更多代碼嗎?你什麼時候運行這條線? – YardenST

+0

謝謝。用相關的代碼更新了這個問題。 – eugene

回答

1

相反動態地添加該字段的,在類適當地定義它:

class EditQuestionForm(PostAsSomeoneForm, PostPrivatelyForm): 
    title = TitleField() 
    tags = TagNamesField() 
    thread_type = forms.ChoiceField(choices=choices, widget=forms.Select) 

當創建的形式實例中設置如果初使值需要:

form = EditQuestionForm(initial={'tread_type': thread_type}) 

如果你不需要這個字段,只需刪除它:

class EditQuestionForm(PostAsSomeoneForm, PostPrivatelyForm): 
    def __init__(self, *args, **kwargs): 
     super(EditQuestionForm, self).__init__(*args, **kwargs) 
     if some_condition: 
      del self.fields['thread_type'] 

當保存形式,檢查:

thread_type = self.cleaned_data['thread_type'] if 'thread_type' in self.cleaned_data else None 

這種方法總是很適合我。

+0

當然可以適應你的做法。如果可能的話,我更喜歡在Form類中設置首字母。因爲什麼使用作爲初始值可能需要相當多的代碼有點,我不希望它在我的意見... – eugene

+0

你仍然可以在類內設置一個初始值,只是出於某種原因,我認爲你需要動態設置它每次 – YardenST

+0

我可以在類中設置初始值,但.is_valid()會引發錯誤,如果該字段是必需的並且給定了初始值,但是沒有給出值 – eugene

相關問題