How to Create a Drop-down List in a Django Form 


               


How to Create a Drop-down List in a Django Form



Python


In this article, we show how to create a drop-down list in a Django form.

A drop-down list is a list that drops down and displays choices in which a user can select one of the choices.

With a drop-down list, only one item in the list can be selected.

Drop-down lists are very popular and widely used in forms.

So how can we create a drop-down list in a Django form?

The following code below can be used to create a drop-down list in a Django form.



So let's go over this code now.

Let's first go to the last line of the code that starts with favorite_fruit.

In this line, we name it favorite_fruit. We give the form a label of, What is your favorite fruit? This is what you will see to the left side of the form field.

Next, we have widget= form.Select(choices=FRUIT_CHOICES))

What this line does is it creates a drop-down list form field, with choices consisting of the list, FRUIT_CHOICES, which you see at the beginning of the code.

When creating choices for a drop-down list, checkbox form, or any form made up of a list of choices, you create a list that consists of tuples.

The tuples are made up of basically key-value or key-Display value pairs. The second value is what is displayed to the user on the form.

So we have the choices, Oranges, Cantaloupes, Mangoes, and Honeydews.

And this is all that is required to create a form field consisting of a drop-down list.

The form that we created above is shown below.


Drop-down list in a Django form





Dynamic Drop-down List of Integers

So in the above code, we showed how to create a drop-down list consisting of strings that we specified directly.

Now we'll go over how to create a dynamic drop-down list of integers in a Django form.

The code is shown below.



So what we've done in this code is we've created a list with the statement, for x in range(1,32) and then converted this list into a tuple. Remember that choices that go into a drop-down list, check boxes, radio buttons, etc. need to be in tuples in Django forms.

So for range(1,32), remember that the first number is inclusive, meaning 1 is included. And the second number is exclusive, meaning that 32 is not included. Therefore, this list goes from 1 to 31, as are days in the longest months of the year.

So you can see how we can dynamically create lists in Django without having to type out all 31 numbers. For lists that are even longer than this, you could see how much time this saves us. Imagine if it was 1 to 100.

So, if we run this code, we would get a form that looks like that shown below.


Dynamic drop-down list of integers in a Django form


We'll show in a later tutorial how to retrieve data from a drop-down list to determine which one was chosen.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...