7

我有这个在我的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))
4

4 回答 4

8

将您的选择移到模型上方,在您的根目录中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存储单词。chevroletChevrolet

如果您只是创建一个表单来保存Marca模型的记录,请使用 a ModelForm,如下所示:

from yourapp.models import Marca

class VehiculoForm(forms.ModelForm):
     class Meta:
         model = Marca

现在,django 将自动呈现选择字段。

于 2013-04-04T04:08:16.170 回答
4

您需要在marcas模型类之外定义选择元组class marca

然后您可以在 forms.py 中执行以下操作以使用

from models import marcas

class addVehiculoForm(forms.Form):
    marca  = forms.CharField(max_length=2, widget=forms.Select(choices= marcas))
    ...
于 2013-04-04T04:03:13.387 回答
0

我更喜欢在模型中保留选择,因此它们不会与其他模型混合。那么解决方案是:

模型.py:

Same as in question.

表格.py:

from yourapp.models import marca

class VehiculoForm(forms.Form):
     marca = forms.ChoiceField(choices=marca.marcas)

     class Meta:
         model = marca
         fields= ('marca')

如果您想要默认模型字段,您也可以只定义元。

于 2018-08-03T12:34:30.367 回答
0

如果选择(元组)像这样初始化为私有属性,还有另一种方法可以做到这一点

模型.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

表格.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',)
于 2020-05-19T07:34:42.797 回答