【问题标题】:What value do I set a Django form's ChoiceField's initial value to be invalid?我将 Django 表单的 ChoiceField 的初始值设置为无效的值是多少?
【发布时间】:2014-01-30 19:56:04
【问题描述】:

我有一个带有两个 ChoiceField 的 Django 表单。我将它们称为 CF1 和 CF2。现在,CF1 显示汽车型号列表。 CF2 保持空白,直到在 CF1 中选择了一个选项,然后我的 JQuery 接管以使用该车型的品牌填充 CF2。示例:日产 -> 千里马。

from django import forms

cars = (('', '----'), ('1', 'Toyota'), ('2', 'Nissan'), ('3', 'Ford'), ('4', 'Honda'))

class SearchForm(forms.Form)
     model = forms.ChoiceField(choices=cars required=True)
     make = forms.ChoiceField(required=True) 

     def clean(self):
         cleaned_data = super(SearchForm, self).clean()
         mo = cleaned_data.get("model")
         ma = cleaned_data.get("make")

         if not mo or not ma:
             raise forms.ValidationError("blahblah")
         return cleaned_data

只有当用户在两个 ChoiceFields 中做出选择时,该表单才被视为有效。但是,无论我是否将选择留空,我提交的表单始终无效。现在,我知道对于 ChoiceField,总是有一个默认的初始值,对吧?但是有没有办法将 ChoiceField 的有效标志设置为无效,直到选择了某些东西,此时该标志被切换为有效?

view.py

def car_info(request):
    form = SearchForm(request.GET) # a form bound to the GET data
    if form.is_valid(): # never seems to be pass this test
        return render(request, "car.html", {})
    else: # always ends up here
        form = SearchForm() # an unbound form
        return render(request, "find.html", {'form': form})

find.html

    {% if form.errors %}
        <div class="err">{{ form.errors | pluralize  }}</div>
    {% endif %}

    <form action="{% url "msite.views.car_info" %}" method="GET" name="listform">
        {{ form.model }}
        {{ form.make }}
        <button>Find</button>
    </form>

【问题讨论】:

  • 希望得到帮助:tech.nickserra.com/2011/06/03/…
  • 感谢您的评论。我确实尝试过,希望它会起作用,但没有。现在,我的 ChoiceField 都带有 '' 值和 '-----' 正在显示。尽管如此,一切都以无效的方式返回。我在我的问题中添加了更多代码。
  • 由于你的第二个 ChoiceField 没有choices,django 不知道如何验证它,这就是它总是失败的原因。您需要覆盖表单的save 方法,以确保两个字段的组合使表单有效或无效。
  • @Burhan Khalid,感谢您的评论。所以你说在我的views.py 中有一个def save(),它基本上检查两个表单字段是否都有选择?我不太确定该怎么做...
  • 不在您的视图中,在您的表单中。请参阅 this section of the documentation,以及您应该自定义的 clean() 而不是 save()

标签: django forms django-forms


【解决方案1】:

您的代码中有一些错误:

class SearchForm(forms.Form)
     model = forms.ChoiceField(choices=cars required=True)
     make = forms.ChoiceField(required=True) 

改为:

class SearchForm(forms.Form)
     model = forms.CharField(max_length=20, choices=cars, default=cars[0][0])
     # add other code if you like

【讨论】:

  • 感谢您的回复。你确定是CharField?我希望它是ChoiceField
猜你喜欢
  • 2011-12-13
  • 2023-03-16
  • 2018-05-22
  • 1970-01-01
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 1970-01-01
  • 2014-12-28
相关资源
最近更新 更多