0

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!

2
  • you mean you want a drop down list populated with all cities? Commented Aug 18, 2019 at 20:03
  • adnanmuttaleb, Hello! Exactly. Cities of those objects that are on the site Commented Aug 18, 2019 at 20:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

adnanmuttaleb, thanks! But, this is not quite right. Your example takes objects from a city model. The city is not a model, this is a field in model. I need to collect data from these fields, and present them in a drop-down list. I apologize if I was incomprehensible.
I have edited the answer @I.Z. Unfortunately your question is a little incomplete, if you provide more details others will be able to help you better.
Excellent! It works! May I ask another question? How to sort correctly if there are three models and all the data needs to be put in one list? Thank!
You are welcome @I.Z., I did not understand you well, I prefer you to post a new question with all necessary details, and hopefully me and the community will answer you. cheers.
Also if you find the solution correct, please do not forget to mark it as correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.