Beginner started learning python and django. I want my dropdown to get data from my dataset

86 Views Asked by At

I'm trying to build a machine learning algorithm and then deploy it to my website using django.So here comes the problem I want drop downs on my forms and. Im using the select tag on html while creating my dropdown but it is very hectic to give each value/option individually. Is there anyway i could get my values from dataset in my dropdowns so i dont have to go through above process.

I imported my model and done it successfully using streamlit. I am expecting to do same with my website that m building in django. I want those values from my dataset that i have loaded in my views.py to be display on my drop down.

enter image description here

1

There are 1 best solutions below

0
On

In django, form classes are provided to make this easier.

What you want is to create a form class with a ChoiceField. You can grab the data in this form rather than the views.py and then create a tuple the choices available from your dataset. We will do this by overriding the form's __init__ field so that load a dynamic set of choices instead of static set of choices.

Example:

from django import forms
from yourapp.models import Brand

class BrandForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(BrandForm, self).__init__(*args, **kwargs)

        brands = Brand.objects.all()
        brand_choices = tuple(i, brand.brand_name for i, brand in enumerate(brands))
        self.fields['brand'] = forms.ChoiceField(choices=brand_choices)

Now in views.py you need to initialize the form and pass it into the context when you call render()

Then just put {{ form }} inside your html form to load all the fields into your form
(if you didnt pass your form into the context as 'form' you will need to change the reference inside of {{ }})

P.s. With a static set of choices, you can define the tuple outside of the class and define the class like this (without needing to override __init__):

class BrandForm(forms.Form):
    brand = forms.ChoiceField(choices=choices)

More examples are available in the django documentation: https://docs.djangoproject.com/en/4.1/topics/forms/