DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Stephen N.
Stephen N.

Posted on

Django Tutorial – Creating Dropdown Menus On Django Forms

I have been teaching myself Python programming for the last couple of years and have recently started learning the Django framework for web development. I will be writing regular posts about some of the challenges I faced and their resolutions. This way, I can review these posts in the future if I need to and possibly benefit others who may experience these same challenges.

This is my first time posting here, so I apologize in advance if there’s anything I miss. For this post, the challenge I faced (and resolved) was creating dropdown menus on Django forms. Below are the steps I followed in doing this; please keep in mind that I created my form using ModelForm.

Step 1: Inside your Django model class, define the different values of your dropdown menu and assign a constant to each value
Dropdown values

Step 2: Still inside your model class, create a list of the values in your dropdown menu. Each item on the list will be a tuple containing two elements. The first element in the tuple is the constant that was created in Step 1 and the second element is the human-readable name. It is the second element (the human readable name) that will be displayed on the Django form for your user.
Values list

Step 3: Add the dropdown field to your database model. Assign your list from step 2 as the value to the keyword argument β€œchoices”. If you want to, you can also set a default value to display for your dropdown menu
Django model

Step 4: In your model form (usually in forms.py), use the β€œSelect” attribute for your dropdown widget
Widget

Step 5: Once you launch your Django form, you should see your dropdown with your values
Django form

Latest comments (0)

πŸ‘‹ Have You Posted on DEV Yet?

Head over to our Welcome Thread and tell us a bit about yourself!