Nick Nash
Nick Nash

Reputation: 57

Select Element in a Django Form

I am learning the Django framework, and I would like to build all of my forms the "Django way" instead of the old fashioned HTML way. Could someone please show me a simple example of how to build a simple select element within a form.py file?

EDIT: I do not care if you down vote this 100 times for being a "noob" question. I simply am asking for one easy example of how to build a select element within a django form. I cannot find any walk through examples on the Django docs, here on Stack Overflow, or elsewhere.

Upvotes: 0

Views: 4370

Answers (1)

Lucid Polygon
Lucid Polygon

Reputation: 572

There are couple of methods to do it, As the question does not explicitly mention how you want your options of select to be populated.

Let's assume you want the options to be hardcoded and then you can do it the following way:

class testForm(forms.Form):
    colors = (
    ('blue', 'Blue'),
    ('green', 'Green'),
    ('black', 'Black'),
)
    select = forms.ChoiceField(choices=colors)

if your options are coming from any model. it can be done by using a ModelChoiceField:

select = forms.ModelChoiceField(queryset=ModelName.objects.all())

Please go through following links and read for the documentation is pretty simple and explained well on how to do these things:

https://docs.djangoproject.com/en/2.0/ref/forms/fields/ https://docs.djangoproject.com/en/2.0/ref/forms/widgets/

Upvotes: 3

Related Questions