Dropdown in Django Model

前端 未结 2 1679
长情又很酷
长情又很酷 2020-12-02 11:03

I want to create a field in Django models.py which will render as a dropdown and user can select the options from there.

If I have 5 choices:

相关标签:
2条回答
  • 2020-12-02 11:41

    From model to template :

    models.py

    COLOR_CHOICES = (
        ('green','GREEN'),
        ('blue', 'BLUE'),
        ('red','RED'),
        ('orange','ORANGE'),
        ('black','BLACK'),
    )
    
    class MyModel(models.Model):
      color = models.CharField(max_length=6, choices=COLOR_CHOICES, default='green')
    

    forms.py

    class MyModelForm(ModelForm):
        class Meta:
            model = MyModel
            fields = ['color']
    

    views.py

    class CreateMyModelView(CreateView):
        model = MyModel
        form_class = MyModelForm
        template_name = 'myapp/template.html'
        success_url = 'myapp/success.html'
    

    template.html

    <form action="" method="post">{% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Create" />
    </form>
    

    or to display your select field only :

    {{ form.color }}
    
    0 讨论(0)
  • 2020-12-02 12:02

    Specify CharField or IntegerField with choices option in your model https://docs.djangoproject.com/en/1.8/ref/models/fields/#choices and use ModelForm https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/.

    0 讨论(0)
提交回复
热议问题