2017-03-06 81 views
0

如何在django泛型listView中检索表单搜索参数。我的网址是:Django:如何在django泛型列表中检索表单搜索参数查看

url(r'postsearch$', views.PostsList.as_view(), name='postsearch'),

我的通用列表视图是:

class PostsList(generic.ListView): 
model = Post 
template_name = 'posts/post_list.html' 

def get_queryset(self): 
    localisation = #how to get location 
    discipline = #how to get discipline 

    return Post.objects.filter(.......) 

,我的形式是:

<form class="form-inline text-center" action="{% url 'posts:postsearch' %}" id="form-searchLessons" method="get"> 
     <div class="form-group"> 
     <input type="text" class="form-control" id="typeCours" list="matieres" placeholder="Matieres: e.g. Math, Physique,.." name="discipline"> 
      <datalist id="matieres"> 
       <option value="value1"> 
       <option value="value2"> 
      </datalist> 
     </div> 
     <div class="form-group"> 
     <input type="text" class="form-control" id="Localisation" placeholder="Lieu: Bousaada, Douaouda,.." 
       name="localisation" onFocus="geolocate()"> 
     </div> 
     <button type="submit" class="btn btn-default" id="btn-getLessons"> 
     <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Trouver ! 
     </button> 
    </form> 

我想根据应用过滤器来获取帖子在搜索字段中引入的lacalisation和matieres(在表格中)

回答

0

您可以将搜索条件添加到url正则表达式中。

url(r'postsearch/(?P<localisation>\w+)/(?P<descipline>\w+)/$', views.PostsList.as_view(), name='postsearch'), 

(注意,心中最后的斜线)

在你get_queryset方法,你可以使用这些给定的URL参数

def get_queryset(self): 
    localisation = self.kwargs['localisation'] or None 
    discipline = self.kwargs['discipline'] or None 
    filters = {} 

    if localisation: 
     filters.update(localisation: localisation) 
    if discipline: 
     filters.update(discipline: discipline) 

    return Post.objects.filter(**filters) 

最终,你应该重新定位让你get_queryset之外的参数,但你决定。

我不确定这样做的安全风险。任何人在此操作过程中都有关于安全风险的更多信息,请分享。

+0

它不承认关键字的本地化和纪律,所以我用json来获取参数 – A2maridz