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