Dropdown in Django Model

依然范特西╮ 提交于 2020-01-30 14:23:12

问题


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:

  • GREEN
  • BLUE
  • RED
  • ORANGE
  • BLACK

How should I write my code in models.py and Forms.py so that the template renders it like a dropdown element?


回答1:


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/.




回答2:


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 }}


来源:https://stackoverflow.com/questions/31130706/dropdown-in-django-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!