试图弄清楚这里出了什么问题。我有一个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 %}
为任何帮助感到高兴!
答案 0 :(得分:0)
您需要使用元组作为您的选择!你关闭但不完全。以下是它的外观:
COLORS = [
('1', 'Röd'),
('2', 'Gul'),
('3', 'Blå')
]
看看是否有效。如果有,请务必将答案标记为正确!
答案 1 :(得分:0)
结果证明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