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モデルのレコードを保存するフォームを作成するだけの場合はModelForm、次のように を使用します。

from yourapp.models import Marca

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

これで、django は選択フィールドを自動的にレンダリングします。

于 2013-04-04T04:08:16.170 に答える