如何使用表单中在模型中声明的choiceField。詹戈

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)

Bur*_*lid 5

将您的选择移至模型上方,位于您的根目录中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将自动呈现选择字段。