D
D
darkglare2021-04-13 15:00:38
Django
darkglare, 2021-04-13 15:00:38

How to set up site search?

Tell me how to search the site news.

Product search works.

Application Search (search by products)

urls.py

from django.conf.urls import url
import django.contrib.auth.views
from search.views import SearchResultsView


urlpatterns = [
    # Examples:
    url(r'^$', SearchResultsView.as_view(), name='search_results'),
    
    ]


views.py

from django.db.models import Q
from django.views.generic import TemplateView, ListView

from shop.models import Product

class SearchResultsView(ListView):
    model = Product
    template_name = 'search/search_results.html'
    
    def get_queryset(self): 
        query = self.request.GET.get('q')
        object_list = Product.objects.filter(
            Q(name__icontains=query) | Q(slug__icontains=query)
        )
        return object_list


search_results.html

...

<div class="row isotope-grid">
                {% for product in object_list %}
                
        <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women">
          <!-- Block2 -->
          <div class="block2">
            <div class="block2-pic hov-img0">
              
                   
                            <a href="{{ product.get_absolute_url }}">
                            <img src="{% if product.image1 %}{{ product.image1.url }}{% else %}{% static 'app/content/products/no_image.png' %}{% endif %}">
                               </a>

              <a href="{{ product.get_absolute_url }}" class="block2-btn flex-c-m stext-103 cl2 size-102 bg0 bor2 hov-btn1 p-lr-15 trans-04 "  >
                Смотреть
              </a>
            </div>

            <div class="block2-txt flex-w flex-t p-t-14">
              <div class="block2-txt-child1 flex-col-l ">
                <a href="{{ product.get_absolute_url }}" class="stext-104 cl4 hov-cl1 trans-04 js-name-b2 p-b-6">
                  {{ product.name }}
                </a>

                <span class="stext-105 cl3">
                  {{ product.price }} руб
                </span>
              </div>

              <div class="block2-txt-child2 flex-r p-t-3">
                <a href="#" class="btn-addwish-b2 dis-block pos-relative js-addwish-b2">
                  <img class="icon-heart1 dis-block trans-04" src="{% static 'app/content/site/images/icons/icon-heart-01.png' %}" alt="ICON">
                  <img class="icon-heart2 dis-block trans-04 ab-t-l" src="{% static 'app/content/site/images/icons/icon-heart-02.png' %}" alt="ICON">
                </a>
              </div>
            </div>
          </div>
        </div>
                           
                {% endfor %}

...


Product Model

class Product(models.Model):

...
    #ОБЩИЕ ХАРАКТЕРИСТИКИ 
    category = models.ForeignKey(Category, related_name='products')
    name = models.CharField(max_length=200, db_index=True, verbose_name="Название")
    slug = models.SlugField(max_length=200, db_index=True)
    image1 = models.FileField(upload_to='products/%Y/%m/%d', blank=True, verbose_name = "Картинка_1")
    image2 = models.FileField(upload_to='products/%Y/%m/%d', blank=True, verbose_name = "Картинка_2")
    image3 = models.FileField(upload_to='products/%Y/%m/%d', blank=True, verbose_name = "Картинка_3")
    ...

class Meta:
        ordering = ('name',)
        index_together = (('id', 'slug'),)

    def get_absolute_url(self):
        return reverse('shop:product_detail',
                        args=[self.id, self.slug])

    def __str__(self):
        return self.name


admin.site.register(Product)

...

Search by product works

By the same principle I do a search by news

urls.py

from django.conf.urls import url
import django.contrib.auth.views
from search_post.views import SearchPosts


urlpatterns = [
    # Examples:
    url(r'^$', SearchPosts.as_view(), name='search_results_posts'),
    
    ]


views.py

from django.db.models import Q
from django.views.generic import TemplateView, ListView


from app.models import Blog

class SearchPosts(ListView):
    model = Blog
    template_name = 'search_post/search_results_posts.html'
    
    def get_queryset(self): 
        query = self.request.GET.get('q')
        object_list_posts = Blog.objects.filter(
            Q(title__icontains=query) | Q(slug__icontains=query)
        )
        return object_list_posts


search_results_posts.html

...

<div class="p-b-63">
                           {% for post in object_list_posts %} 
                  <a href="{% url 'blogpost'  parametr=post.id %}" class="hov-img0 how-pos5-parent ">
               	
                               
                                <img class="hov-img0 how-pos5-parent" src="{{post.image.url}}" alt="Картинка"  />
                                
                <div class="flex-col-c-m size-123 bg9 how-pos5">
                  <span class="ltext-107 cl2 txt-center">
                    
                  </span>

                  <span class="stext-109 cl3 txt-center">
                    
                  </span>
                </div>
              </a>
                            
              <div class="p-t-32">
                                
                                
                
                  <p class="ltext-108 cl2 hov-cl1 trans-04">
                    {{post.title}}
                  
                

                <p class="stext-117 cl6">
                  {{post.description}}
                </p>
                                
                <div class="flex-w flex-sb-m  m-b-35"> <!--Тут я задал расстояние между картинками статьи блога m-b-50  (margin-bottom) и убрал p-t-18-->
                                    
                  <span class="flex-w flex-m stext-111 cl2 p-r-30 m-tb-10">
                    <span>
                      <span class="cl4">By</span> {{post.author}} 
                      <span class="cl12 m-l-4 m-r-6">|</span>
                    </span>
                                        

                    <span>
                      {{post.posted}}  
                      <span class="cl12 m-l-4 m-r-6">|</span>
                    </span>

                    <span>
                      {{ posts.comment_set.count }} Комментариев
                    </span>
                  </span>

                  <a href="{% url 'blogpost'  parametr=post.id %}" class="stext-101 cl2 hov-cl1 trans-04 m-tb-10">
                                        Читать далее
                       <i class="fa fa-long-arrow-right m-l-9"></i>
                  </a>
                </div>
                            {% endfor %}
                               {% if object_list_posts %}
                {% else %}
                <h2> В новостях ничего не найдено</h2>
                {% endif %}
              </div>

...


Model Blog

class Blog(models.Model):
    title = models.CharField(max_length = 100, unique_for_date = "posted", verbose_name = "Заголовок")
    slug = models.SlugField(max_length=200, db_index=True)
    description = models.TextField(verbose_name = "Краткое содержание")
    content = models.TextField(verbose_name = "Полное содержание" ,)
    posted = models.DateTimeField(default = datetime.now(),db_index = True, verbose_name = "Опубликована")
    author = models.ForeignKey(User, null=True, blank=True, on_delete = models.SET_NULL, verbose_name = "Автор")
    image = models.FileField(default = 'temp.jpg', verbose_name = "Путь к картинке")

   

    def get_absolute_urls(self): #метод возвращает строку с уникальным интернет адресом записи
        return reverse("blogpost", args=[str(self.id)])

    def __str__(self):
        return self.title # метод возвращает название используемое для представления отдельных заголовков
    
    class Meta:
        db_table = "Posts" # имя таблицы для модели
        ordering = ["-posted"] # порядок сортировки данных в модели (- означает по убыванию)
        verbose_name = "статья блога" # имя под окторым модель будет отображаться в админ разделе
        verbose_name_plural = "статьи блога" # тоже для всех статей блога

admin.site.register(Blog)


But the news list is not displayed, what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wolf_girl, 2021-04-13
@Wolf_girl

object_list_posts = Blog.objects.filter(Q(title__icontains=query) | Q(slug__icontains=query))

I think instead of slug__icontains you need to write content__icontains

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question