Django文檔說當在窗體上使用ModelChoiceField時,表單被設置爲required = False,並且模型被設置爲blank = True,除了沒有默認值,那麼我應該會收到一個空的空選項我的選擇標籤。我不是。任何想法,我已經做了什麼,失去了空的選擇?Django - ModelChoiceField空選擇丟失
models.py
class Location(models.Model):
location_name = models.CharField(max_length=50, blank=True)
address = models.CharField(max_length=50)
active = models.BooleanField(default=True)
def __unicode__(self):
return self.location_name
forms.py
class CalcForm(forms.Form):
startAddr = forms.ModelChoiceField(queryset=Location.objects.all(), required=False)
waypoint1 = forms.ModelChoiceField(queryset=Location.objects.all(), required=False)
waypoint2 = forms.ModelChoiceField(queryset=Location.objects.all(), required=False)
...
endAddr = forms.ModelChoiceField(queryset=Location.objects.all(), required=False)
template.html
<form action="../calcview" method="get">{% csrf_token% }
<label>
<div>Start Address</div>
<select name="startAddr">
{% for location in form.fields.startAddr.queryset %}
<option value = "{ location.location_name }">{{location.location_name}}/option>
{% end for %}
</select>
...
</form>
謝謝,這就是解決方案。 – Joe