Reputation: 127
I'm new to django and would like to create a drop down menu for options. I'm confused as to what I should include in my forms.py and how to call that form on my index.html.
My forms.py
from django import forms
class MyModel2(forms.Form):
class Meta:
model = MyModel
fields = ['color']
My index.html
<form method="POST" action = "">{% csrf_token %}
<p>Choose color</p> {{ form.color}}
<br><br>
<input type="submit" value="Submit!"/>
</form>
My models.py
from __future__ import unicode_literals
from django.db import models
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')
Thank you!
Upvotes: 1
Views: 14576
Reputation: 1860
First use ModelForm
instead of Form
, then you can use widgets
attributes:
from django.forms import ModelForm
# Mind the name of your form!!
class MyModelForm(ModelForm):
class Meta:
model = MyModel
fields = ['color']
widgets = {
# Here you define what input type should the field have
'color': Select(attrs = {
'class': 'form-control',
}),
}
You don't "call that form on my index.html". Yo use views
to call the form and set the html template to use.
Using class based views you got:
from django.views.generic import CreateView
from .models import MyModel
from .forms import MyModelForm
class ColourCreateView(CreateView):
model = MyModel
template_name = 'index.html'
form_class = MyModelForm
Upvotes: -1
Reputation: 53
Widgets are probably the answer here, but you don't necessarily need to use a ModelForm (unless, as it seems like, you are wanting to use models with you form, but you don't have to.) Try something like this:
# forms.py
class MyModel2(forms.Form):
color = forms.CharField(widget=forms.Select)
and...
<!-- index.html -->
<form method="POST" action = "ACTION_OR_VIEW_URL_ON_SUBMIT_HERE">{% csrf_token %}
<label for="colorSelect">Choose color</label>
<select type="text" id="colorSelect" name="colorSelect">
<option selected>GREEN</option>
<option>BLUE</option>
<option>RED</option>
<option>ORANGE</option>
<option>BLACK</option>
</select>
<br><br>
<input type="submit" value="Submit!"/>
</form>
Or, if you do want to use a ModelForm, check out guillermo chamorro's answer to see how to use widgets with them.
Upvotes: 1
Reputation: 1490
So your only problem is that you declared your model field as a CharField
while trying to use a forms.Form
for your form instead of a forms.ModelForm
. If you're going to use forms.Form
you'll need to declare a ChoiceField to get a select dropdown automatically.
You could also make use of forms.ModelForm
instead of forms.Form
in your form and I'm pretty sure that would make it work as well. ModelForm and Forms don't handle fields the same way unfortunately.
Upvotes: 2