Evgenii Legotckoi
Jan. 16, 2018, 1:19 p.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.

  1. 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.

  1. <form class="input-group" method="get">
  2. <input name="q" type="text" class="form-control" placeholder="Search Forums" value="{{ q }}">
  3. <span class="input-group-btn">
  4. <button type="submit" class="btn btn-default">Search</button>
  5. </span>
  6. </form>
  7.  
  8. {% 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.

  1. # -*- coding: utf-8 -*-
  2.  
  3. from django.conf.urls import url
  4.  
  5. from . import views
  6.  
  7. app_name = 'forum'
  8. urlpatterns = [
  9. url(r'^$', views.IndexView.as_view(), name='index'),
  10. ]

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.

  1. '''
  2. Advanced search keys
  3. '''
  4. ARTICLE = 'article'
  5.  
  6. class IndexView(View):
  7. template_name = 'forum/index.html'
  8.  
  9. def get(self, request):
  10. q = self.request.GET.get('q')
  11. if q:
  12. try:
  13.   # Try to break the search query into a key / value pair
  14. key, value = q.split(':')
  15.   # If it was possible and there is no exception, then we check whether the key is valid and whether the value is a number
  16. if key == ARTICLE and value.isdigit():
  17.   # If yes, then we filter the topics by external key of articles
  18. object_list = Topic.objects.filter(article__pk=value).order_by('-lastmod')
  19. else:
  20.   # otherwise, throw an exception
  21. raise ValueError
  22. except ValueError:
  23.   # 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
  24. object_list = Topic.objects.filter(
  25. Q(title__icontains=q) |
  26. Q(content__icontains=q) |
  27. Q(forumpost__content__icontains=q)
  28. ).distinct().order_by('-lastmod')
  29. else:
  30.   # if there is no search query, then we perform the usual selection of articles
  31. object_list = Topic.objects.all().order_by('-lastmod')
  32.  
  33. return render(
  34. request=request,
  35. template_name=self.template_name,
  36. context={
  37. 'q': q or '',
  38. 'object_list': get_paginated_page(request, object_list, 40),
  39. 'last_question': request.get_full_path().replace(request.path, '') # url for pagination with regard to the question
  40. }
  41. )

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,

  1. <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 .

Do you like it? Share on social networks!

AK
  • March 4, 2022, 4:46 p.m.

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html