Hug*_*oya 3 django django-models django-forms choicefield
我有这个 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
Run Code Online (Sandbox Code Playgroud)
我需要在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))
Run Code Online (Sandbox Code Playgroud)
将您的选择移至模型上方,位于您的根目录中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)
Run Code Online (Sandbox Code Playgroud)
然后在文件中声明以下形式:
from yourapp.models import marcas
class VehiculoForm(forms.Form):
marca = forms.ChoiceField(choices=marcas)
Run Code Online (Sandbox Code Playgroud)
我还为您解决了其他一些问题:
max_length字符字段的,因为只要chevrolet有人Chevrolet在选项下拉列表中进行选择,您就可以随时存储单词。如果您只是创建一个表单来保存Marca模型记录,请使用ModelForm,如下所示:
from yourapp.models import Marca
class VehiculoForm(forms.ModelForm):
class Meta:
model = Marca
Run Code Online (Sandbox Code Playgroud)
现在,django将自动呈现选择字段。
| 归档时间: |
|
| 查看次数: |
10390 次 |
| 最近记录: |