4

正确定义“其他”选项我对django和python都很陌生,目前正试图构建一个带有各种选项的表单,以及不在列表中的选项的“其他”选项。我想定义选项,以便当选中“其他”时,表单仅在其他文本框包含非空值的情况下进行验证。在Django MultipleChoiceField中正确定义使用CheckboxSelectMultiple

有没有适当的方式来扩展Django窗体/领域/部件来实现这一目标?搜索google和stackoverflow后找到的最接近的东西是this example,它提供了扩展代码来创建自定义渲染器,窗口小部件和表单字段,但它基于旧版本的django。

回答

4

如果您使用django.forms.ModelForm来呈现您的表单,则可以在选项字段的表单验证(clean_[your field name])中执行此操作。

from django import forms 

class YourModelForm(forms.ModelForm): 
    def clean_your_options(self): 
     your_options = self.cleaned_data.getlist('your_options') 

     if 'other' in your_options: 
      other_text_input = self.cleaned_data.get('other_text_input') 
      if len(other_text_input) == 0: 
       raise forms.ValidationError('Other text input must contain value') 

     return your_options 
+0

我只是使用普通的旧django.forms.Forms。你的答案是否适用于这种情况? – Dave 2012-07-26 14:39:04

+0

是的,它应该工作得很好:https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute – mVChr 2012-07-26 14:48:24

+0

感谢您的帖子!这看起来比我想要的要容易得多。今晚晚些时候我会再试一次。 – Dave 2012-07-26 14:50:47

相关问题