简体   繁体   English

将参数传递给Django中的ListView

[英]Passing a parameter to a ListView in Django

I have a HTML drop list with certain values that I want to pass to my generic view in order to return a filtered list. 我有一个HTML下拉列表,其中包含要传递给我的通用视图的某些值,以便返回过滤后的列表。

The class: 班级:

 class filteredListView(generic.ListView): template_name = 'guestlist/guestlist.html' def get_queryset(self, **kwargs): relation = kwargs.get('relation', None) if relation == 'all': return Guest.objects.all() if relation == 'grooms_side': return Guest.objects.filter(grooms_side=True) if relation == 'brides_side': return Guest.objects.filter(brides_side=True) if relation == 'friends': return Guest.objects.filter(friends=True) 

html block: html块:

 <th colspan="4"> <label>Filter by Relation <select onchange="location='filtered'"> <option value="all">All</option> <option value="grooms_side">Groom's Side</option> <option value="brides_side">Brides's Side</option> <option value="friends">Friends</option> </select> </label> </th> 

I've tried passing the value with a normal href like a regular view but that gave me a NoReverseMatch exception. 我已经尝试通过普通href如常规视图)传递值,但这给了我NoReverseMatch异常。

urls.py: urls.py:

 from django.conf.urls import url from . import views app_name = 'guestlist' urlpatterns = [ # /guestlist/ url(r'^$', views.indexView.as_view(), name='index'), # /guestlist/ url(r'^guestlist/$', views.guestListView.as_view(), name='guestlist'), # /guestlist/add url(r'^guestlist/add/$', views.guestCreate.as_view(), name='add'), # /guestlist/filtered url(r'^guestlist/filtered$', views.filteredListView.as_view(), {'relation': 'relation'}, name='filtered'), ] 

My question is how do i pass the value from the drop list's options to the view. 我的问题是如何将值从下拉列表的选项传递到视图。 Thanks. 谢谢。

Edit: I've changed a few things according to one of the answers but the question still stands. 编辑:我已经根据答案之一更改了一些内容,但问题仍然存在。 What do I put in the dict in urls.py in order to pass the value? 为了传递值,我应该在urls.py中放入dict吗?

You need to use a form to send the value from the dropdown to the filter view. 您需要使用表格将值从下拉列表发送到过滤器视图。 And there is no reason to put anything in the URL pattern itself. 并且没有理由在URL模式本身中放入任何内容。

url(r'^guestlist/filtered$', views.filteredListView.as_view(), name='filtered'),


<th colspan="4">
  <form action="{% url filtered %}" method="GET">
  <label>Filter by Relation
    <select name="relation">
      <option value="all">All</option>
      <option value="grooms_side">Groom's Side</option>
      <option value="brides_side">Brides's Side</option>
      <option value="friends">Friends</option>
    </select>
  </label>
  <input type="submit" value="Filter">
  </form>
</th>

and in the view: 并在视图中:

def get_queryset(self, **kwargs):
    relation = self.request.GET.get('relation', None)
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM