django - 如何在表单中使用模型中声明的 choiceField。 Django

标签 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

我需要在我的 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 , 像这样:
    from yourapp.models import Marca
    
    class VehiculoForm(forms.ModelForm):
         class Meta:
             model = Marca
    

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

    关于django - 如何在表单中使用模型中声明的 choiceField。 Django ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15802254/

    相关文章:

    python - 无法使用 DRF APIClient() 更改 header

    python - 如何在不发送信号的情况下保存模型?

    python - 是否可以在 django 管理站点中更改模型名称?

    django - 使用 Django 用户管理员使电子邮件字段独一无二

    python - Django 管理员 : How to get all values from 2 models with same FK

    python - 多对多查询 (Django)

    python - django - 获取用于调用 django View 的确切 GET url(包括参数)

    css - 将单个元素插入重复网格

    没有秒的Django TimeField模型

    python - 为什么我的表格总是未绑定(bind)?