如何在基于类的列表视图上创建搜索功能?

时间:2019-07-03 06:39:36

标签: django

我正在尝试根据帖子标题创建搜索功能。现在,我正在尝试使用过滤器实现此搜索,但列表视图未呈现。我不确定是否应该为搜索功能实现URL。

这是我的模特

class Post(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(default = 'default0.jpg', upload_to='course_image/')
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=6)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
feedback = models.ManyToManyField(Feedback)

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('post-detail', kwargs={'pk' : self.pk})

这是我基于班级的列表视图:

class PostListView(ListView):
model = Post
template_name = 'store/sub_home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['date_posted']
paginate_by = 12

def get_queryset(self):
    object_list = super(PostListView, self).get_queryset()
    search = self.request.GET.get('q', None)
    if search:
        object_list = object_list.filter(title__icontains = title)
    return object_list

这是我的搜索栏:

<div id="search">
<form method='GET' action=''>
  <input type="text" name='q' placeholder="">
  <button id='search_holder'>
    <img src="/static/store/search_icon.gif" id="search_icon">        
  </button>
</form>
</div>

这是呈现帖子的我的html:

{% extends "store/base.html" %}  
{% block content %}
{% include "store/home_ext.html" %}
<div style="padding-top: 20px;" id="main" >
<section class="text-center mb-4">
  <div class="row" id="random"> 
    {% for post in posts %}   
    {% include "store/card.html" %}
    {% endfor %}
  </div>
  <div class="row" id="subscription" style="display: none;">
    {% if not subs %}
    <h2>You have not subscribed to any course :/</h2>
    {% endif %} 
    {% for post in subs %}
    {% include "store/card.html" %}
    {% endfor %}
  </div>
  <div class="row" id="content" style="display: none;"> 
    {% if not mine %}
    <h2>You have not published anything :/</h2>
    {% endif %}   
    {% for post in mine %}
    {% include "store/card.html" %}
    {% endfor %}
  </div>
</section>
{% include "store/pagination.html" %}
</div>
{% endblock content %}

这是我的card.html:

{% load extra_filter %}
<div class="col-lg-3 col-md-6 mb-4">            
        <div id="course_card">            
          <div class="view overlay">
            <img style="margin-left: -10px;" src="{{ post.image.url }}" alt="">
          </div>                                    
          <div>                

            <div>
              <strong>
                {% if user.is_authenticated %}
                <a class="title" href="{% url 'post-detail' post.id %}" >
                {% else %}
                <a class="title" href="{% url 'login' %}" >
                {% endif %}
                  {% if post.title|length < 30 %}
                  <span>{{ post.title }}</span> 
                  {% else %}
                  <span>{{ post.title|cut:27 }}</span>
                  {% endif %}
                  <span  style="background-color: rgb(253, 98, 98);" class="badge badge-pill danger-color">NEW
                  </span> 
                </a>
              </strong>
            </div>

             <div class="star-ratings-css">
            <div class="star-ratings-css-top" style="width: {{ post.feedback|calc_rating }}%"><span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></div>
            <div class="star-ratings-css-bottom"><span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></div>
            </div>

            <a href="{% url 'user-posts' post.author.username %}" class="author">
              by {{ post.author }} 
            </a>

           <div>
              <strong style="text-align: right;" class="price">S${{ post.price }}
              </strong>
            </div>
            <small class="date">
               {{ post.date_posted|date:'d F y'}}
            </small>
          </div>            
        </div>            
      </div>   

1 个答案:

答案 0 :(得分:1)

正如Nalin Dobhal在评论中所述,context_object_name应该为posts而不是post。因为在模板中,您正在遍历posts上下文变量。另外,使用搜索功能时,实现应如下所示:

class PostListView(ListView):
    model = Post
    template_name = 'store/sub_home.html' # /_.html
    context_object_name = 'posts'
    ordering = ['date_posted']
    paginate_by = 12

    def get_queryset(self, *args, **kwargs):
        object_list = super(PostListView, self).get_queryset(*args, **kwargs)
        search = self.request.GET.get('q', None)
        if search:
            object_list = object_list.filter(title__icontains = search)
        return object_list

因为您要通过URL querystring发送搜索查询(即,URL在浏览器中看起来像/posts/?q=title)。我正在使用request.GET.get('q')来获取那些查询字符串值,并使用它来过滤查询集。