Reputation: 197
There is a model field, city
, it is filled manually when creating the
object.
There is a field in the search form, city
. In views.py it looks like this:
views.py:
if 'city' in request.GET:
city = request.GET['city']
if city:
queryset_list = queryset_list.filter(city__iexact=city)
template.html:
<div class="col-md-4 mb-3">
<label class="sr-only">City</label>
<input type="text" name="city" class="form-control" placeholder="City">
</div>
If you enter the name of the city, objects with that name will be selected. It works correctly, but it’s inconvenient.
I want the city not to be entered, but selected from the list. This list should be automatically collected from the fields city. How can this be implemented? Thank!
Upvotes: 0
Views: 777
Reputation: 3604
You have not included enough details about your models, but you can get what you using something like that:
Your view:
from django.shortcuts import render
def myview(request):
#get your list of cities you may also do some filtering
cities = [obj.city for obj in YourModel.objects.all()]
return render(request, 'cities_template.html', {'cities': cities})
your template (cities_template.html):
<select>
{% for city in cities %}
<option value={{city}}>{{city}}</li>
{% endfor %}
</select>
If you provide more details, I may help you better, cheers.
Upvotes: 2