Django-如何显示模型&x27;s选项作为复选框
我遵循了,但仍然无法在表单上显示选项作为复选框 models.pyDjango-如何显示模型&x27;s选项作为复选框,django,django-models,django-forms,Django,Django Models,Django Forms,我遵循了,但仍然无法在表单上显示选项作为复选框 models.py class Car(models.Model): TYPE_CHOICES = ( ('s', 'small'), ('m', 'medium'), ('b', 'big'), ) type = models.CharField(max_length=1, choices=TYPE_CHOICES) class Notification(models.Mod
class Car(models.Model):
TYPE_CHOICES = (
('s', 'small'),
('m', 'medium'),
('b', 'big'),
)
type = models.CharField(max_length=1, choices=TYPE_CHOICES)
class Notification(models.Model):
platforms = models.CharField(max_length=30, blank=False)
forms.py
from django import forms
from django.forms.widgets import CheckboxSelectMultiple
from cars.models import Car
class AddCar(forms.ModelForm):
class Meta:
model = Car
type = forms.MultipleChoiceField(choices=Car.TYPE_CHOICES, widget=forms.CheckboxSelectMultiple())
您使用的是
路线。风景选项
不是汽车。键入选项
您需要使用表单。RadioSelect()
而不是表单。复选框SelectMultiple()
,因为它是单值的
要覆盖ModelForm的小部件
或者像你的问题一样,type
行应该在class Meta
行的上方,在AddCar
class AddCar(forms.ModelForm):
type = forms.ChoiceField(choices=Car.SCENERY_CHOICES, widget=forms.RadioSelect)
class Meta:
model = Car
那是表格
class AddCarForm(forms.Form):
type = forms.MultipleChoiceField(required=False,
widget=forms.CheckboxSelectMultiple, choices=TYPE_CHOICES)
这是表格的格式
class AddCar(forms.ModelForm):
type = forms.MultipleChoiceField(required=False,
widget=forms.CheckboxSelectMultiple, choices=TYPE_CHOICES)
class Meta:
model = Car
然后在模板中,这是非常重要的使用这个
{{ form.type }}
i、 e不要像html那样调用
类型
如果你真的想使用multiple select,而不使用任何自定义字段,这就是我在类似场景中所做的。
警告:数据库中存储的值违反了正常格式。但由于它应该是2-3个值的字符串(增长的机会非常小,我更喜欢这种快速破解)
我所做的是,该模型只使用了CharField,而不考虑它的用途。另一方面,ModelForm处理多项选择逻辑
在我的“models.py”中
在“forms.py”中
如果选中这两个复选框,则存储在数据库列中的数据将是字符串“ios,android”。否则,它将是“ios”、“android”。正如我所说,当然不是正常化。如果有一天你的领域有很多价值,事情可能会变得很糟糕 他可以使用复选框输入。应该使用。因此,在您的示例中应该使用:
widgets={'type':forms.CheckboxInput}
@marianobianchi恐怕不行,CheckboxInput
小部件用于布尔值。
class Notification(models.Model):
platforms = models.CharField(max_length=30, blank=False)
class NotificationForm(forms.ModelForm):
class Meta(object):
model = models.Notification
platforms = forms.MultipleChoiceField(initial='android', choices=(('ios', 'iOS'), ('android', 'Android')), widget=forms.CheckboxSelectMultiple)
def __init__(self, *args, **kwargs):
instance = kwargs['instance']
# Intercepting the instance kw arg, and turning it into a list from a csv string.
if instance is not None:
instance.platforms = instance.platforms.split(",")
kwargs['instance'] = instance
super(NotificationForm, self).__init__(*args, **kwargs)
# Do other stuff
def clean(self):
cleaned_data = super(NotificationForm, self).clean()
platforms = cleaned_data['platforms']
# Convert the list back into a csv string before saving
cleaned_data['platforms'] = ",".join(platforms)
# Do other validations
return cleaned_data