Django ChoiceField populated from database values
Asked Answered
J

5

18

I am having problems using a ChoiceField to create a drop down list of values in the database. Here is the snippet of code

from django import forms
from testplatform.models import ServiceOffering

class ContactForm(forms.Form):

    subject = forms.ChoiceField(queryset=ServiceOffering.objects.all())
    #subject = forms.ModelMultipleChoiceField(queryset=ServiceOffering.objects.all())

The #subject.... line works, but when I use the line ChoiceField(queryset....) I get the following error.

__init__() got an unexpected keyword argument 'queryset'

Any ideas?

Jard answered 13/8, 2012 at 14:34 Comment(0)
Z
38

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

Zigzagger answered 13/8, 2012 at 14:35 Comment(2)
Excellent - that worked a treat. I get a ------ as a default value in the drop down box. Can I change that? Thanks!Jard
If shows that way if the field is optional, set the field on the form to required=True to remove it.Zigzagger
M
7

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

Malamud answered 16/4, 2015 at 7:55 Comment(0)
C
3

Use the ModelChoiceField Link Here

ChoiceField doesn't support queryset

Cordierite answered 13/8, 2012 at 14:45 Comment(2)
thanks - got it.. I suppose I can use the initial value so I don't see the ------ appear?Jard
@Jard Yeah you can use the initial value to get rid of ---- set initial = "Some value"Cordierite
M
1

view.py :- This is my view.py file. And create below code.

def add_customer(request):
    objectlist = Vehicle.objects.values('brand_name').distinct().order_by('brand_name')
    if request.method == 'POST':
        form = CustomerForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/show-customers')
    else:
        form = CustomerForm()
    return render(request, 'add-customer.html', {'form':form, 'objectlist':objectlist})

Customer.html

<select name="prefer_car_model" id="id_prefer_car_model" required>
                <option value="0" selected disabled> Select Car model </option>
                {% for obj in objectlist %}
                <option value="{{ obj.brand_name }}">{{ obj.brand_name }} </option>
                {% endfor %}
            </select>

Output

VMS - Vehicle Brand Name Lists

Moriahmoriarty answered 20/5, 2019 at 11:42 Comment(1)
Hi Thai, adding a bit more explanation around your solution, rather than merely posting code, would make it a great response.Timepiece
M
0

In Django 2+ you can use 'choices' instead of 'queryset'

Mailable answered 7/2, 2020 at 20:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.