Django - Tutorial 032. Advanced search options

Django, Search

The site has functional, thanks to which you can ask a question on the forum with an article on the site to which this question relates in one way or another. This is done through external keys from the topic on the site's forum to articles. In this case, the foreign key may not be.

article = models.ForeignKey(Article, verbose_name=_("Статья"), null=True, blank=True)

Thus, at the end of the article you can see how many questions on the forum are given for this article. This allows you to improve the page linking of the site, and also gives users the opportunity to find similar questions about the article they are studying.

The main question for me was how to implement a list of topics on the forum so as not to overload the site with additional pages that would complicate the navigation. The solution was simple enough: add a search option on the forum with additional advanced search keys. Namely, the article key, which would define the article id , for which you want to filter out all topics on the forum that contain a foreign key for an article with this id .

This approach allowed to change the main page of the forum, to expand the functionality of the forum with an additional search and to exclude the addition of a new presentation and template for new pages.


In the layout itself, I will not go into depth, it's not so important, I will show only the layout for the search form.

<form class="input-group" method="get">
    <input name="q" type="text" class="form-control" placeholder="Search Forums" value="{{ q }}">
    <span class="input-group-btn">
        <button type="submit" class="btn btn-default">Search</button>

{% include 'forum/partials/index_topics_list.html' %}

For layout, use bootstrap 3 . In the template for the main page of the forum there is a template for displaying a list of forum topics, as well as a form for entering a search query. In this case, the get method is used for the query.

A query can be a common word or phrase or a key:value . In this case, the pair will look like this: article:95 .

q is the text of the search query, respectively.

In this solution, only one key pair and value are processed. This is enough for my purposes.

There is nothing special in the path manager.

# -*- coding: utf-8 -*-

from django.conf.urls import url

from . import views

app_name = 'forum'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),

The search for the extended key is done through an exception, that is, if it is not possible to allocate a key / value pair, then we try to use a normal search.

Advanced search keys
ARTICLE = 'article'

class IndexView(View):
    template_name = 'forum/index.html'

    def get(self, request):
        q = self.request.GET.get('q')
        if q:
                # Try to break the search query into a key / value pair
                key, value = q.split(':')
                # If it was possible and there is no exception, then we check whether the key is valid and whether the value is a number
                if key == ARTICLE and value.isdigit():
                    # If yes, then we filter the topics by external key of articles
                    object_list = Topic.objects.filter(article__pk=value).order_by('-lastmod')
                    # otherwise, throw an exception
                    raise ValueError
            except ValueError:
                # With the exception, we do a regular search for the title of the topics, the content of topics and the content of messages in forum topics
                object_list = Topic.objects.filter(
                    Q(title__icontains=q) |
                    Q(content__icontains=q) |
            # if there is no search query, then we perform the usual selection of articles
            object_list = Topic.objects.all().order_by('-lastmod')

        return render(
                'q': q or '',
                'object_list': get_paginated_page(request, object_list, 40),
                'last_question': request.get_full_path().replace(request.path, '') # url for pagination with regard to the question

You can read about the function get_paginated_page in the article about reloading part of the page content .

Thus, you can implement as a link to forum questions related to the article,

<a href="{% url 'forum:index' %}?q=article:{{ }}">

and advanced search keys in the style of well-known search engines.

For Django I recommend VDS-server of Timeweb hoster .

10% refund of hotel reservation amount on Booking
10% refund of hotel reservation amount on Booking
We offer a link with a 10% return on the amount of the order when booking a hotel through Booking
Support the author Donate


Only authorized users can post comments.
Please, Log in or Sign up
May 19, 2019, 1:49 a.m.

Qt - Test 001. Signals and slots

  • Result:78points,
  • Rating points2
May 17, 2019, 1:14 p.m.

Qt - Test 001. Signals and slots

  • Result:42points,
  • Rating points-8
May 17, 2019, 4:18 a.m.

C++ - Тест 003. Условия и циклы

  • Result:57points,
  • Rating points-2
Last comments
May 21, 2019, 8:10 p.m.

Приветствую! Я думаю дойдёт и до этого, но пока изучать его у меня нет желания.
May 20, 2019, 7:20 p.m.
Евгений Легоцкой

Добрый день! Вы не думали разместить репозиторий проекта на GitHub?
May 18, 2019, 2:03 p.m.

Спасибо большое! Вскоре буду разбираться!
May 18, 2019, 9:13 a.m.
Евгений Легоцкой

Добрый день! Отнимать значение общего счётчика можно в деструкторе класса кнопки QDynamicButton::~QDynamicButton(){ ResID--;} При этом я бы ещё переустанавливал значения вс...
May 14, 2019, 10:33 p.m.

Здравствуйте!А не подскажите, как можно при удалении какой либо кнопки, у щётчика отнять значение?Дабы например четвёртой кнопке соответствовал ID 4, а не 5 скажем
Now discuss on the forum
May 24, 2019, 6:48 a.m.
Евгений Легоцкой

Если там будут только перечисления внутри namespace, то жа, достаточно будет заголовочного файла
May 24, 2019, 6:28 a.m.
Андрей Янкович

работает любой http сервер, и можно использовать обсалютно любой портпример <RemoteRepositories> <Repository> <Url>;
May 23, 2019, 2:40 p.m.

Попробовал сделать этот запрос по http и получил json файл. request.setUrl(QUrl("")); Как Вы думаете, почему https не работает и как это и...
May 23, 2019, 10:42 a.m.

Спасибо, помогло.
May 23, 2019, 6:31 a.m.
Евгений Легоцкой

Для задач и граф-то не нужен. Достаточно будет таблицы в локальной базе данных SQLite, в которой указывается задача, время и т.д. В этом разделе есть примеры по работа с базой д...

For registered users on the site there is a minimum amount of advertising

Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB