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:
How should I write my code in models.py
and Forms.py
so that the template renders it like a dropdown element?
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.
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> .
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 }}
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/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With