Categories
Python Answers

How to create a dropdown in Python Django model form?

Spread the love

Sometimes, we want to create a dropdown in Python Django model form.

In this article, we’ll look at how to create a dropdown in Python Django model form.

How to create a dropdown in Python Django model form?

To create a dropdown in Python Django model form, we can create a char field with the choices argument set to a tuple of choices in a model class.

Then we can set the model class as the model for the form.

For instance, we write

models.py

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')

to add the color field to the MyModel model class.

Then in forms.py, we write

class MyModelForm(ModelForm):
    class Meta:
        model = MyModel
        fields = ['color']

to create the MyModelForm that adds the color field as a field in the form.

And we set the model class to MyModel.

Then in views.py, we write

class CreateMyModelView(CreateView):
    model = MyModel
    form_class = MyModelForm
    template_name = 'myapp/template.html'
    success_url = 'myapp/success.html'

to add the CreateMyModelView view class to render MyModelForm.

In template.html, we add

<form action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Create" />
</form>

to render the form.

Conclusion

To create a dropdown in Python Django model form, we can create a char field with the choices argument set to a tuple of choices in a model class.

Then we can set the model class as the model for the form.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to create a dropdown in Python Django model form?”

{{ form.as_p }} – where did we define the ‘form’ object?
in views.py we created ‘form_class = MyModelForm’ , should we use form_class instead of ‘form’ then?

Leave a Reply

Your email address will not be published. Required fields are marked *