How to Create Radio Buttons in a Django Form


In this article, we show how to create radio buttons in a Django form.

Radio buttons are a group on buttons on a form that allows a user to make a choice. Only one radio button can be selected.

Unlike check boxes, which can allow for multiple items to be selected, with radio buttons, only one item can be selected.

So how can we create radio buttons in a Django form?

The following code below can be used to create radio buttons 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.RadioSelect(choices=FRUIT_CHOICES))

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

When creating choices for a radio button form, checkbox form, 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 radio buttons.

The form that we created is shown below.

Radio buttons in a Django form

We'll show in a later tutorial how to retrieve data from a group of radio buttons 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...