1

我尝试使用 django 实现过滤器选项我可以进行过滤,但在刷新后无法保留所选选项,因为我正在渲染过滤后的结果,有什么解决方案吗?

视图.py

def filter(request):
    products = Product.objects.all()
    print(products)
    if request.method == 'POST':
      title = request.POST.get('da',None)
      print(title)
      titre = Product.objects.filter(title=title)
      print(titre)
      return render(request, 'searchapp/searchview.html', {'qs': titre,'ds':products})



    return render(request,'searchapp/searchview.html',{'qs':products})

html:

<div>
    <form action="{% url 'search:query' %}" method="post" enctype="multipart/form-data">
      {% csrf_token %}
            <div class="form-group">
                <label>Title</label>
                  <select name="da" class="form-control">
                        {% for obj in qs %}
                 <option value="{{obj}}">{{obj}}</option>
                         {%endfor%}

                         </select>
            </div>
            <button type="submit" class="btn btn-warning btn-lg">Add Product</button>
        </form>
</div>

4

2 回答 2

1

解决方案是使用 GET :

视图.py

def filter(request):
      products = Product.objects.all()
      print(products)
      title = request.GET.get('da',None)
      print(title)
      titre = Product.objects.filter(title=title)
      print(titre)
      return render(request, 'searchapp/searchview.html', {'qs': titre,'ds':products})



      return render(request,'searchapp/searchview.html',{'qs':products})

html.py

   <form action="{% url 'search:query' %}" method="GET" enctype="multipart/form-data">
      {% csrf_token %}
            <div class="form-group">
                <label>Title</label>
                  <select name="da" id="da" class="form-control">
                        {% for obj in ds %}
                 <option value="{{obj}}">{{obj}}</option>
                         {%endfor%}
<!--                <input type="text" class="form-control" name="title">-->
                         </select>
            </div>
            <button type="submit" class="btn btn-warning btn-lg">Add Product</button>
        </form>
</div>

于 2020-03-06T20:48:03.063 回答
0

Django Admin Filters 使用 GET 请求。这解决了你的问题:

title = request.GET.get('da',None)
<form action="{% url 'search:query' %}" method="get" enctype="multipart/form-data">
于 2020-03-06T20:27:57.937 回答