[英]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.