Evgenii Legotckoi
Evgenii LegotckoiJan. 16, 2018, 2:19 a.m.

Django - Tutorial 032. Advanced search options

Content

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.


Template

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>
    </span>
</form>

{% 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.

urls.py

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'),
]

views.py

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:
                # 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')
                else:
                    # 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) |
                    Q(forumpost__content__icontains=q)
                ).distinct().order_by('-lastmod')
        else:
            # if there is no search query, then we perform the usual selection of articles
            object_list = Topic.objects.all().order_by('-lastmod')

        return render(
            request=request,
            template_name=self.template_name,
            context={
                '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:{{ article.pk }}">

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

For Django I recommend VDS-server of Timeweb hoster .

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

AK
  • March 4, 2022, 5:46 a.m.

Добрый день!
Помогите советом: есть таблица (over 150.000 записей) по которой хотелось бы вести поиск по трем полям не усложняя жизнь пользователю вводом форматированных запросов.
Поле поиска одно, в котором пользователь может ввести как данные из одного поля, так и их сочетание.
Как-то это реализуемо или я много хочу?)

Comments

Only authorized users can post comments.
Please, Log in or Sign up
MB

Qt - Test 001. Signals and slots

  • Result:57points,
  • Rating points-2
MB

C++ - Test 001. The first program and data types

  • Result:60points,
  • Rating points-1
GK

C++ - Test 005. Structures and Classes

  • Result:0points,
  • Rating points-10
Last comments
J
JonnyJoJune 8, 2023, 12:14 p.m.
Qt/C++ - Lesson 019. How to paint triangle in Qt5. Positioning shapes in QGraphicsScene Евгений, здравствуйте! Решил поэкспериментировать немного с кодом из этого урока, нарисовать вместо треугольника квадрат и разобраться с координатами. В итоге, запутался. И ни документация,…
J
JonnyJoMay 25, 2023, 2:24 p.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю!
Evgenii Legotckoi
Evgenii LegotckoiMay 25, 2023, 4:49 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Код на строчка 184-198 вызывает перерисовку области на каждый 4-й такт счётчика. По той логике не нужно перерисовывать объект постоянно, достаточно реже, чем выполняется игровой слот. А слот вып…
J
JonnyJoMay 21, 2023, 10:49 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю! Всё равно не совсем понимаю :( Если муха двигает ножками только при нажатии клавиш перемещение, то что, собственно, делает код со строк 184-198 в triangle.cpp? В этих строчка…
Evgenii Legotckoi
Evgenii LegotckoiMay 21, 2023, 5:57 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Добрый день. slotGameTimer срабатывает по таймеру и при каждой сработке countForSteps увеличивается на 1, это не зависит от нажатия клавиш, нажатая клавиша лишь определяет положение ножек, котор…
Now discuss on the forum
T
TwangerJune 7, 2023, 11:12 a.m.
Ошибка при выполнении триггерной функции (GreenPlum) Есть 3 таблицы fact_amount со структурой: CREATE TABLE fact_amount ( id serial4 NOT NULL, fdate date NULL, type_activity_id int4 NULL, status_id int4 NULL, CONSTRAINT fact…
AR
Alexander RyabikovJune 6, 2023, 1:35 p.m.
Работа с QFileSystemModel Вопросик по теме QFileSystemModel в Linux. Он, как и положено, обновляется самостоятельно, если директория локальная. Но, вот, сетевая папка (у меня шара samba) не обновляется. Как её можно…
Evgenii Legotckoi
Evgenii LegotckoiApril 16, 2023, 4:07 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Да, это возможно. Но подобные вещи лучше запускать через celery. То есть drf принимает команду, и после этого регистрирует задачу в celery, котроый уже асинхронно всё это выполняет. В противном …
АБ
Алексей БобровDec. 14, 2021, 7:03 p.m.
Sorting the added QML elements in the ListModel I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …

Follow us in social networks