Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropdown in Django Model

I want to create a field in Django models.py which will render as a dropdown and user can select the options from there.

If I have 5 choices:

  • GREEN
  • BLUE
  • RED
  • ORANGE
  • BLACK

How should I write my code in models.py and Forms.py so that the template renders it like a dropdown element?

like image 593
S7H Avatar asked Jun 30 '15 06:06

S7H


People also ask

How to add dropdown in django models?

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. to add the color field to the MyModel model class.

What is widget in Django?

A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting <! DOCTYPE html> .


2 Answers

From model to template :

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

forms.py

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

views.py

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

template.html

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

or to display your select field only :

{{ form.color }} 
like image 186
Val F. Avatar answered Sep 28 '22 03:09

Val F.


Specify CharField or IntegerField with choices option in your model https://docs.djangoproject.com/en/dev/ref/models/fields/#choices and use ModelForm https://docs.djangoproject.com/en/dev/topics/forms/modelforms/.

like image 34
f43d65 Avatar answered Sep 28 '22 02:09

f43d65