我有一个带两个ChoiceFields的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>
答案 0 :(得分:0)
您的代码中存在一些错误:
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