Django ChoiceField populated from database values Django ChoiceField populated from database values django django

Django ChoiceField populated from database values


ChoiceField doesn't have a queryset. You're looking for ModelChoiceField


if you want to populate dropdown list from database, I'll recommend you to pass all the values in single object from views.py to your template. You can do it this way:1] fetch all the values from database:

objectlist = ModelName.objects.all()

if you want sorted list in dropdown list, Do this:

objectlist = ModelName.objects.all().order_by('fieldname')

if you want distinctlist, do this:

objectlist = ModelName.objects.distinct('fieldname')

2] Pass this render this 'objectlist' with template

return render(request, 'template.html', {'objectlist': objectlist})

3] In template use a select tag , and in user for loop to iterate over the objectlist.

<select>{% for element in objectlist %}<option value={{ element.id }}>{{ element.name }}     </select>

value in option tag depends on what you need to process in your API


Use the ModelChoiceField Link Here

ChoiceField doesn't support queryset