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
- How to assign to a Django PointField model attribute?
- Pycharm Django Debugging is really slow
- Django: default language i18n
- How to filter filter_horizontal in Django admin?
- Clean Up HTML in Python
- Python Social Auth Django template example
- Django + Forms: Dynamic choices for ChoiceField
- Installing Django with pip
- Method in Django to display all attributes' values belonging to a created object?
- Django global variable
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
- 'WSGIRequest' object has no attribute 'session' while upgrading from django 1.3 to 1.9
- Django & TastyPie: request.POST is empty
- Relation does not exist error in Django
- Django, REST and Angular Routes
- Google.maps.event.addDomListener() is deprecated, use the standard addEventListener() method instead : Google Place autocomplete Error
Source:stackexchange.com