在django中给出初始值提升'字段值'是必需的'错误

时间:2013-08-20 07:42:41

标签: django forms field

Django形式多次绊倒我......

我给ChoiceField(Form类的 init

提供了初始值
self.fields['thread_type'] = forms.ChoiceField(choices=choices, 
    widget=forms.Select, 
    initial=thread_type)  

使用上述代码thread_type创建的表单不会传递is_valid(),因为'此字段(thread_type)是必需的'。

CNC中
找到了解决办法,但它仍然让我很困惑。

我的模板中有代码

   {% if request.user.is_administrator() %}
      <div class="select-post-type-div">                                                                                                                                                                                                                                        
        {{form.thread_type}}                                                                                                                                                                                                                                                    
      </div> 
   {% endif %}

当提交此表单时,如果用户不是admin,则request.POST没有'thread_type'。

view函数使用以下代码创建表单:

form = forms.MyForm(request.POST, otherVar=otherVar)

我不明白为什么通过以下(与上面相同)给出初始值是不够的。

self.fields['thread_type'] = forms.ChoiceField(choices=choices, 
        widget=forms.Select, 
        initial=thread_type)  

并且,在thread_type中包含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)

1 个答案:

答案 0 :(得分: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

这种方法对我来说总是很有效。