问题
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