通过下拉值的选定选项的值,以Django的数据库

问题描述 投票:2回答:2

我工作在一个Django项目。我想提出一个HTML表单(不使用Djnango形式)。现在,我可以(只是通过给名称输入标签,并通过从views.py访问它们)通过的“文字”输入到数据库中使用“POST”方法的值。但我有问题,做同样的,当它涉及到一个下拉菜单的响应。我有一个下拉菜单,从中,用户可以选择多个选项。现在,我怎样检测由用户选择的选项,并通过他们的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>   
python html django forms django-forms
2个回答
0
投票

由于问题是开放的,你有很多选择。这里有两个非常简单的解决方案

最简单的,使用qazxsw POI。文档是qazxsw POI。

如果您需要更多的控制,你可以使用特定的部件。查看文档ChoiceFiled


0
投票
here

here


编辑

形式(模板)

<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
© www.soinside.com 2019 - 2024. All rights reserved.