[英]Django Form Error: Select a valid choice. … is not one of the available choices
[英]Django form error: “Select a valid choice” on RadioSelect()
試圖找出這里出了什么問題。 我有一個ModelForm,需要在三種顏色之間進行單選。 我收到以下錯誤:
“選擇一個有效的選擇。這不是可用的選擇之一”
models.py:
COLORS = (
('1', 'Röd'),
('2', 'Gul'),
('3', 'Blå'),)
class Poster(models.Model):
title = models.CharField(max_length=100)
colors = models.IntegerField(choices=COLORS, default=2)
forms.py:
class PosterForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PosterForm, self).__init__(*args, **kwargs)
class Meta:
model = Poster
fields = ('title', 'colors')
labels = {
"title": "Rubrik",
"colors": "Färg",
}
widgets = {
'colors': forms.RadioSelect(attrs={'choices': "[(1, 'Röd'), (2, 'Gul'),(3, 'Blå')]"}),
}
template.html:
<div id="id_colors">
<div class="radio"><label for="id_colors_0"><input class="" id="id_colors_0" name="colors" title="" type="radio" value="1" required /> Röd</label></div>
<div class="radio"><label for="id_colors_1"><input checked="checked" class="" id="id_colors_1" name="colors" title="" type="radio" value="2" required /> Gul</label></div>
<div class="radio"><label for="id_colors_2"><input class="" id="id_colors_2" name="colors" title="" type="radio" value="3" required /> Blå</label></div>
</div>
{% if form.colors.errors %}
<div class="alert alert-danger">
<strong>{{ form.colors.errors|escape }}</strong>
</div>
{% endif %}
樂於助人!
您需要使用元組進行選擇! 您已經接近,但還沒來得及。 外觀如下:
COLORS = [
('1', 'Röd'),
('2', 'Gul'),
('3', 'Blå')
]
看看是否可行。 如果正確,請確保正確標記答案!
事實證明,IntegerField不太喜歡String內的數字值。 將這種方法更改為使用字母和CharField可以解決問題。
models.py:
COLORS = (
('r', 'Röd'),
('y', 'Gul'),
('b', 'Blå'),)
class Poster(models.Model):
title = models.CharField(max_length=100)
colors = models.CharField(choices=COLORS, max_length=1)
forms.py:
class PosterForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PosterForm, self).__init__(*args, **kwargs)
class Meta:
model = Poster
fields = ('title', 'colors')
labels = {
"title": "Rubrik",
"colors": "Färg",
}
widgets = {
*'colors': forms.RadioSelect(),*
}
template.html:
<div id="id_colors">
<div class="radio"><label for="id_colors_0"><input class="" id="id_colors_0" name="colors" title="" type="radio" value="r" required /> Röd</label></div>
<div class="radio"><label for="id_colors_1"><input checked="checked" class="" id="id_colors_1" name="colors" title="" type="radio" value="y" required /> Gul</label></div>
<div class="radio"><label for="id_colors_2"><input class="" id="id_colors_2" name="colors" title="" type="radio" value="b" required /> Blå</label></div>
</div>
{% if form.colors.errors %}
<div class="alert alert-danger">
<strong>{{ form.colors.errors|escape }}</strong>
</div>
{% endif %}
感謝Cheng的這篇帖子對我有所幫助: http : //cheng.logdown.com/posts/2015/05/25/django-create-a-radio-input-using-bootstrap3s-inline-style
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.