Passing the value of selected option of dropdown value to django database
14,036
<option value="{{ city.id }}">{{city.city_name}}</option>
http://www.w3schools.com/tags/tag_option.asp
EDIT
form (template)
<form action="/" method="post"> {% csrf_token %}
<p>Enter City (hold Ctrl to select more than one)</p>
<label for="optCity" class="sr-only">Select City to be shipped to</label><br>
<select multiple class="form-control" id="optCity" name="city" required>
{% for city in all_cities %}
<option value="{{city.id}}">{{city.name}}</option>
{% endfor %}
</select>
<p><input type="submit" value="Send form"/></p>
</form>
view
def form_view(request):
context = {
'all_cities': City.objects.all()
}
if request.POST:
city_pk_list = request.POST.getlist('city', None)
print(request.POST.getlist('city', None))
selected_city_obj_list = City.objects.filter(pk__in=city_pk_list)
print(selected_city_obj_list)
return render(request, 'index.html', context=context)
model
class City(models.Model):
name = models.CharField(max_length=512)
def __unicode__(self):
return self.name
Assume it renders
<option value="1">Kyiv</option>
<option value="2">Lviv</option>
<option value="3">Odessa</option>
<option value="4">New York</option>
<option value="5">Tbilisi</option>
And I've selected Kyiv
and Odessa
So in output will be
[u'1', u'3']
[<City: Kyiv>, <City: Odessa>]
Author by
vhd
Updated on June 23, 2022Comments
-
vhd almost 2 years
I am working on a Django project. I am making an HTML form (not using the Djnango forms). Now, I am able to pass the values of "text" inputs to the database using the "POST" method (just by giving the name to the input tag, and by accessing them from views.py). But I have problem doing the same when it comes to the response of a dropdown menu. I have a dropdown menu, from which, a user can select multiple options. Now, how do I detect the options selected by the user and pass them to views.py so that I can add them into the database from there?
Here is the code of the dropdown menu.
Enter City (hold Ctrl to select more than one) <label for="inputCity" class="sr-only">Select City to be shipped to</label><br> <select multiple class="form-control" id="optCity" name="city" required> {% for city in all_cities %} <option>{{city.city_name}}</option> {% endfor %} </select><br>
-
vhd almost 9 yearsThanks, it helps... but the thing is, that I want the object of "City" type to be returned. if I put value="{{city.city_name}}", it returns the string named a particular city (let's say c1 - string). But I have multiple choices c1, c2, c3 - which are all "city" type objects. And apparently, it shows that the dropdown is not returning the "city" type object. What should I do ?