Answer the question
In order to leave comments, you need to log in
Django model search implementation, how to make it show a list of articles that match the query?
Model search results are not displayed
The model itself, which should be:
models.py
class Articles(models.Model):
title = models.CharField(max_length = 120, verbose_name = "Заголовок")
post = models.TextField(verbose_name = "Текст")
image = models.ImageField(blank=True, upload_to='images/blog/%Y/%m/%d', help_text='150x150px',
verbose_name='Ссылка картинки')
date = models.DateTimeField(verbose_name = "Дата")
category = models.ForeignKey(Category, null = True, blank = True, on_delete = models.SET_NULL, verbose_name = "Категория") #cjplfybt мягкой связи, когда удаление вторичного объекта не приводит к удалению первичного
# Добвление лайков
likes = models.IntegerField(verbose_name='Нравится', default=0)
dislikes = models.IntegerField(verbose_name='Не нравится', default=0)
class Meta:
verbose_name_plural = "Статьи"
def __str__(self):
return self.title
from django.views.generic import ListView
from django.db.models import Q
from news.models import Articles
class ArticleListView(ListView):
model = Articles
template_name = 'search/index.html'
def get_queryset(self):
# Получаем не отфильтрованный кверисет всех моделей
queryset = Articles.objects.all()
q = self.request.GET.get("q")
if q:
# Если 'q' в GET запросе, фильтруем кверисет по данным из 'q'
return queryset.filter(Q(title__icontains=q) | Q(post__icontains=q))
return queryset
from django.conf.urls import url
from . import views
from .views import ArticleListView
urlpatterns = [
url(r'^article_search/', ArticleListView.as_view(), name='article_search'),
]
<form action="{% url 'article_search' %}" class="navbar-form navbar-left" method="get">
<div class="form-group">
<input type="text" name="q" class="form-control" placeholder="Введите запрос">
</div>
<button type="submit" class="btn btn-default">Поиск</button>
</form>
{% extends "mainApp/wrapper.html" %}
{% block content %}
<h1>Поиск</h1>
{% if article in article_lists %}
{% for article in article_lists %}
<article>
<a href="{{ article.get_absolute_url }}">
<h2>{{ article.article_title }}</h2>
</a>
{{ article.post|safe }}
<p><a class="btn btn-default btn-sm" href="{{ article.get_absolute_url }}">Читать далее</a></p>
</article>
{% endfor %}
{% else %}
<p>Не найдено публикаций по вашему запросу<br>Попробуйте повторить запрос с другой формулировкой</p>
{% endif %}
{% endblock %}
Answer the question
In order to leave comments, you need to log in
{% if article in article_lists %} - it doesn't do what you expect :)
{% extends "mainApp/wrapper.html" %}
{% block content %}
<h1>Поиск</h1>
{% for article in article_lists %}
<article>
<a href="{{ article.get_absolute_url }}">
<h2>{{ article.article_title }}</h2>
</a>
{{ article.post|safe }}
<p><a class="btn btn-default btn-sm" href="{{ article.get_absolute_url }}">Читать далее</a></p>
</article>
{% empty %}
<p>Не найдено публикаций по вашему запросу<br>Попробуйте повторить запрос с другой формулировкой</p>
{% endfor %}
{% endblock %}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question