我在model.py
class marca(models.Model):
marcas = (
('chevrolet', 'Chevrolet'),
('mazda', 'Mazda'),
('nissan', 'Nissan'),
('toyota', 'Toyota'),
('mitsubishi', 'Mitsubishi'),
)
marca = models.CharField(max_length=2, choices= marcas)
def __unicode__(self):
return self.marca
我需要在我的form.py
中使用它
我尝试了这个,但它不起作用。
class addVehiculoForm(forms.Form):
placa = forms.CharField(widget = forms.TextInput())
tipo = forms.CharField(max_length=2, widget=forms.Select(choices= tipos_vehiculo))
marca = forms.CharField(max_length=2, widget=forms.Select(choices= marcas))
答案 0 :(得分:4)
将您的选择移到models.py
marcas = (
('chevrolet', 'Chevrolet'),
('mazda', 'Mazda'),
('nissan', 'Nissan'),
('toyota', 'Toyota'),
('mitsubishi', 'Mitsubishi'),)
class Marca(models.Model):
marca = models.CharField(max_length=25,choices=marcas)
然后在您声明表单的文件中:
from yourapp.models import marcas
class VehiculoForm(forms.Form):
marca = forms.ChoiceField(choices=marcas)
我还为你解决了一些其他问题:
max_length
,因为只要有人在选择下拉菜单中选择chevrolet
,您就会存储单词Chevrolet
。如果您只是创建表单来保存Marca
模型的记录,请使用ModelForm
,如下所示:
from yourapp.models import Marca
class VehiculoForm(forms.ModelForm):
class Meta:
model = Marca
现在,django将自动呈现选择字段。
答案 1 :(得分:3)
您需要在模型类marcas
之外定义选择元组class marca
。
然后你可以在forms.py中使用
from models import marcas
class addVehiculoForm(forms.Form):
marca = forms.CharField(max_length=2, widget=forms.Select(choices= marcas))
...
答案 2 :(得分:0)
我更喜欢将选择保留在模型内部,因此不会与其他模型混淆。那么解决方案将是:
models.py:
Same as in question.
forms.py:
from yourapp.models import marca
class VehiculoForm(forms.Form):
marca = forms.ChoiceField(choices=marca.marcas)
class Meta:
model = marca
fields= ('marca')
如果要使用默认模型字段,也可以只定义元。
答案 3 :(得分:0)
如果将选择(元组)初始化为私有属性,则还有另一种方法
models.py
class Marca(models.Model):
__marcas = ( #private attributes
('chevrolet', 'Chevrolet'),
('mazda', 'Mazda'),
('nissan', 'Nissan'),
('toyota', 'Toyota'),
('mitsubishi', 'Mitsubishi'),
)
marca = models.CharField(max_length=100, choices= __marcas)
def __unicode__(self):
return self.marca
forms.py
from yourapp.models import Marca #import model instead of constant
class VehiculoForm(forms.Form):
marca = forms.ChoiceField(choices= Marca._meta.get_field('marca').choices)
#If you want to get the default model field
#or just straight get the base field (not prefer solution)
marca = Marca._meta.get_field('marca')
#or define in class Meta (prefer and better solution)
class Meta:
model = Marca
fields = ('marca',)