search.py
45 lines
| 1.2 KiB
| text/x-python
|
PythonLexer
|
r718 | from django.shortcuts import render | ||
from django.views.generic import View | ||||
|
r1849 | from django.db.models import Q | ||
|
r917 | |||
|
r718 | from boards.abstracts.paginator import get_paginator | ||
from boards.forms import SearchForm, PlainErrorList | ||||
|
r1729 | from boards.models import Post | ||
|
r718 | |||
|
r917 | |||
MIN_QUERY_LENGTH = 3 | ||||
RESULTS_PER_PAGE = 10 | ||||
|
r721 | FORM_QUERY = 'query' | ||
CONTEXT_QUERY = 'query' | ||||
CONTEXT_FORM = 'form' | ||||
CONTEXT_PAGE = 'page' | ||||
REQUEST_PAGE = 'page' | ||||
|
r718 | __author__ = 'neko259' | ||
TEMPLATE = 'search/search.html' | ||||
class BoardSearchView(View): | ||||
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: | ||
|
r1849 | results = Post.objects.filter(Q(text__icontains=query) | | ||
Q(title__icontains=query)).order_by('-id') | ||||
|
r917 | paginator = get_paginator(results, RESULTS_PER_PAGE) | ||
|
r718 | |||
|
r917 | page = int(request.GET.get(REQUEST_PAGE, '1')) | ||
|
r718 | |||
|
r917 | params[CONTEXT_PAGE] = paginator.page(page) | ||
params[CONTEXT_QUERY] = query | ||||
return render(request, TEMPLATE, params) | ||||