刷新页面后如何保持选择的选项

时间:2020-03-06 20:14:26

标签: html django django-3.0

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

views.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>

2 个答案:

答案 0 :(得分:1)

解决方案是使用GET:

views.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>

答案 1 :(得分:0)

Django管理员过滤器使用GET请求。那解决了您的问题:

example
title = request.GET.get('da',None)