在 Django 视图中检索 Select2 多值以在后端使用

Retrieve Select2 multi values in Django Views to use in backend

我的 html 中有一个可用的 Select2 Multi Dropdown,但如何将这些值带回 Django 以在后端使用?

例如在我的 html 中,我有:

<script>
    $(document).ready(function()
    {
        $("#ddlselect").select2({
            placeholder:'Select from List',
            closeOnSelect:false
        });

    });
</script>

然后我用以下代码填充下拉列表:

        <select id="ddlselect" multiple="multiple" style="width: 250px;">
            {% for item in mylist %}
                <option> {{ item }} </option>
            {% endfor %}
        </select>

这行得通,我可以从下拉列表中进行选择。

我可以在 html 中使用以下方法检索值:

<script>
function myFunction() {
  alert("Selected value is: "+$("#ddlselect").select2("val"));
}
</script>

现在,如何将这些值带回我的 Django 视图?

我试过以下 -

class newoption(TemplateView):

   template_name = 'home/page.html'
   
   def get(self, request):

      return render(request, self.template_name, dict)

   def post(self, response):
        a = response.POST['ddlselect']

我在尝试 return 在后端使用时遇到错误。如何从 select2MultiSelect 中检索选定的值?

您可以使用getlist()方法:

Returns a list of the data with the requested key. Returns an empty list if the key doesn’t exist and default is None. It’s guaranteed to return a list unless the default value provided isn’t a list.

self.request.POST.getlist('ddlselect')

像这样:

from django.http import HttpResponse

class NewOption(TemplateView):
    
    ...

    def post(self, request, *args, **kwargs):
        ddl = request.POST.getlist('ddlselect')
        ... Some code here ...
        return HttpResponse("Submitted!")

同时将 name 属性添加到您的 html select:

<select name="ddlselect" id="ddlselect" multiple="multiple" style="width: 250px;">
...
</select>