2011-06-20 99 views
20

主視圖是一個簡單的分頁ListView,我想向它添加一個搜索表單。Django基於視圖ListView與表格

我覺得這樣的事情會做的伎倆:

class MyListView(ListView, FormView): 
    form_class = MySearchForm 
    success_url = 'my-sucess-url' 
    model = MyModel 
    # ... 

但很顯然我聽錯了..我無法找到如何做到這一點的官方文檔。

對此提出建議?

回答

5

我一直在尋找適當的解決方案。但找不到任何必須拿出我自己的。 views.py

class VocationsListView(ListView): 

    context_object_name = "vocations" 
    template_name = "vocations/vocations.html" 
    paginate_by = 10 

    def get_queryset(self): 
     get = self.request.GET.copy() 
     if(len(get)): 
      get.pop('page') 
     self.baseurl = urlencode(get) 
     model = Vocation 
     self.form = SearchForm(self.request.GET) 
     filters = model.get_queryset(self.request.GET) 
     if len(filters): 
      model = model.objects.filter(filters) 
     else: 
      model = model.objects.all() 
     return model 



def get_context_data(self, **kwargs): 
    context = super(VocationsListView, self).get_context_data(**kwargs) 
    context['form'] = self.form 
    context['baseurl']= self.baseurl 
    return context 

models.py

class Vocation(models.Model): 
    title = models.CharField(max_length = 255) 
    intro = models.TextField() 
    description = models.TextField(blank = True) 
    date_created = models.DateTimeField(auto_now_add = True) 
    date_modified = models.DateTimeField(auto_now = True) 
    created_by = models.ForeignKey(User, related_name = "vocation_created") 
    modified_by = models.ForeignKey(User, related_name = "vocation_modified") 

    class Meta: 
     db_table = "vocation" 

    @property 
    def slug(self): 
     return defaultfilters.slugify(self.title) 

    def __unicode__(self): 
     return self.title 

    @staticmethod 
    def get_queryset(params): 

     date_created = params.get('date_created') 
     keyword = params.get('keyword') 
     qset = Q(pk__gt = 0) 
     if keyword: 
      qset &= Q(title__icontains = keyword) 
     if date_created: 
      qset &= Q(date_created__gte = date_created) 
     return qset 

所以基本上我這一段代碼添加到每個模型類,在這裏我想實現搜索功能。這是因爲對於每一個模型過濾器必須被明確地準備

@staticmethod 
def get_queryset(params): 

    date_created = params.get('date_created') 
    keyword = params.get('keyword') 
    qset = Q(pk__gt = 0) 
    if keyword: 
     qset &= Q(title__icontains = keyword) 
    if date_created 
     qset &= Q(date_created__gte = date_created) 
    return qset 

它準備,我用它來從模型

26

這些答案已經幫助這麼多引導我的檢索數據展示Qset過濾器正確的方向。謝謝你們。

對於我的實現,我需要一個表單視圖,它在get和post上都返回一個ListView。 我不喜歡重複get函數的內容,但它需要一些更改。該表單現在也可以通過self.form從get_queryset獲得。

from django.http import Http404 
from django.utils.translation import ugettext as _ 
from django.views.generic.edit import FormMixin 
from django.views.generic.list import ListView 

class FormListView(FormMixin, ListView): 
    def get(self, request, *args, **kwargs): 
     # From ProcessFormMixin 
     form_class = self.get_form_class() 
     self.form = self.get_form(form_class) 

     # From BaseListView 
     self.object_list = self.get_queryset() 
     allow_empty = self.get_allow_empty() 
     if not allow_empty and len(self.object_list) == 0: 
      raise Http404(_(u"Empty list and '%(class_name)s.allow_empty' is False.") 
          % {'class_name': self.__class__.__name__}) 

     context = self.get_context_data(object_list=self.object_list, form=self.form) 
     return self.render_to_response(context) 

    def post(self, request, *args, **kwargs): 
     return self.get(request, *args, **kwargs) 


class MyListView(FormListView): 
    form_class = MySearchForm 
    model = MyModel 
    # ... 
+0

完美!我不得不交換繼承順序tho(ListView,FormMixin)以保持分頁工作。 – laffuste

+0

這是很好,但我應該在模板中使用輸出所有窗體。我只看到第一個元素的一個表單實例和作爲模型列表的objects_list。 –

+4

你能列出模板代碼嗎? –

0

從以前的答案,這是我拿上我以作爲ListView控件在同一頁上顯示的形式使用的觀點:

class IndexView(FormMixin, ListView): 
    ''' Homepage: displays list of links, and a form used to create them ''' 
    template_name = "links/index.html" 
    context_object_name = "links" 
    form_class = LinkForm 

    def get_queryset(self): 
     return Links.objects.all() 

def add_link(request): 
    # Sole job of this function is to process the form when POSTed. 
    if request.method == "POST": 
     form = LinkForm(request.POST) 

     if form.is_valid(): 
      Links.objects.create(address=form.cleaned_data['address']) 

     return HttpResponseRedirect('/') 

之後,最後一件事是將add_link綁定查看功能的表單的動作網址,你很好去我想。