我正在研究Django项目。我正在制作HTML表单(不使用Djnango表单)。现在,我可以使用“POST”方法将“text”输入的值传递给数据库(只需将名称赋给输入标记,并从views.py访问它们)。但是当涉及到下拉菜单的响应时,我遇到了同样的问题。我有一个下拉菜单,用户可以从中选择多个选项。现在,如何检测用户选择的选项并将它们传递给views.py,以便我可以从那里将它们添加到数据库中?
以下是下拉菜单的代码。
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>
答案 0 :(得分:0)
<option value="{{ city.id }}">{{city.city_name}}</option>
http://www.w3schools.com/tags/tag_option.asp
表单(模板)
<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>
查看强>
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)
<强>模型强>
class City(models.Model):
name = models.CharField(max_length=512)
def __unicode__(self):
return self.name
假设它呈现
<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>
我已选择Kyiv
和Odessa
因此在输出中将是
[u'1', u'3']
[<City: Kyiv>, <City: Odessa>]
答案 1 :(得分:0)