在Django中传递参数

时间:2019-01-16 13:28:23

标签: django forms search

我正在django中实现搜索功能,并且我想使用ListView。如何将搜索字符串传递给views.py中的函数? 这是我要修改的视图函数:

class PersonList(ListView):

    model=Person
    context_object_name='persons'

这是模板:

<form class="form-inline my-2 my-lg-0" name="search" action="{% url 'artdb:search' %}" method="post">{% csrf_token %}
      <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" value="{{name}}">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>r code here

1 个答案:

答案 0 :(得分:0)

    class PersonList(ListView):
        model = Person
        template_name = 'your-template-name.html'
        context_object_name='persons'

        def get_queryset(self):
            search_string = self.request.GET.get('search',None)
            if search_string is None:
                persons = Person.objects.filter()                    
            else:
                persons = Person.objects.filter(name__icontains=search_string)enter code here
            return persons

您需要在模板中添加它。

<form class="form-inline my-2 my-lg-0" action="{% url 'artdb:search' %}" method="get">{% csrf_token %}
      <input class="form-control mr-sm-2" type="text" placeholder="Search" name="search" aria-label="Search" value="{{search}}">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
 </form>

在您的urls.py

从django.conf.urls导入URL

urlpatterns = [

url(r'^ search-result $',views.PersonList.as_view(),name ='search'),

]