我的里面有这个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))
将您的选择移至模型之上,位于您的根部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 https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelform, 像这样:
from yourapp.models import Marca
class VehiculoForm(forms.ModelForm):
class Meta:
model = Marca
现在,django 将自动渲染选择字段。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)