search.py
54 lines
| 1.7 KiB
| text/x-python
|
PythonLexer
|
r718 | from django.shortcuts import render | ||
from django.views.generic import View | ||||
|
r1849 | from django.db.models import Q | ||
|
r1986 | from django.urls import reverse | ||
|
r917 | |||
|
r718 | from boards.abstracts.paginator import get_paginator | ||
from boards.forms import SearchForm, PlainErrorList | ||||
|
r1950 | from boards.models import Post, Tag | ||
|
r1878 | from boards.views.mixins import PaginatedMixin | ||
|
r718 | |||
|
r917 | |||
MIN_QUERY_LENGTH = 3 | ||||
RESULTS_PER_PAGE = 10 | ||||
|
r721 | FORM_QUERY = 'query' | ||
CONTEXT_QUERY = 'query' | ||||
CONTEXT_FORM = 'form' | ||||
CONTEXT_PAGE = 'page' | ||||
|
r1950 | CONTEXT_TAGS = 'tags' | ||
|
r721 | |||
REQUEST_PAGE = 'page' | ||||
|
r718 | __author__ = 'neko259' | ||
TEMPLATE = 'search/search.html' | ||||
|
r1878 | class BoardSearchView(View, PaginatedMixin): | ||
|
r718 | def get(self, request): | ||
|
r917 | params = dict() | ||
|
r718 | form = SearchForm(request.GET, error_class=PlainErrorList) | ||
|
r917 | params[CONTEXT_FORM] = form | ||
|
r718 | |||
if form.is_valid(): | ||||
|
r721 | query = form.cleaned_data[FORM_QUERY] | ||
|
r917 | if len(query) >= MIN_QUERY_LENGTH: | ||
|
r1877 | results = Post.objects.filter(Q(text__icontains=query) | ||
| Q(title__icontains=query) | Q(opening=True, | ||||
|
r1982 | thread__tags__aliases__name__icontains=query) | ||
| Q(attachments__url__icontains=query)).order_by('-id').distinct() | ||||
|
r917 | paginator = get_paginator(results, RESULTS_PER_PAGE) | ||
|
r1878 | paginator.set_url(reverse('search'), request.GET.dict()) | ||
|
r718 | |||
|
r917 | page = int(request.GET.get(REQUEST_PAGE, '1')) | ||
|
r718 | |||
|
r917 | params[CONTEXT_QUERY] = query | ||
|
r1878 | params.update(self.get_page_context(paginator, page)) | ||
|
r917 | |||
|
r1950 | tags = Tag.objects.get_tag_url_list(Tag.objects.filter(aliases__name__icontains=query)) | ||
params[CONTEXT_TAGS] = tags | ||||
|
r917 | return render(request, TEMPLATE, params) | ||