diff --git a/conntrackt/views.py b/conntrackt/views.py --- a/conntrackt/views.py +++ b/conntrackt/views.py @@ -27,6 +27,7 @@ from zipfile import ZipFile, ZIP_DEFLATE from django.contrib.auth.decorators import permission_required from django.contrib import messages from django.core.urlresolvers import reverse, reverse_lazy +from django.db.models import Q from django.http import HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.views.generic import TemplateView, DetailView, CreateView, UpdateView, DeleteView @@ -965,3 +966,54 @@ def project_diagram(request, pk): # Return the response object. return response + + +class SearchView(MultiplePermissionsRequiredMixin, TemplateView): + """ + Custom view used for rendering the search (results) page. + """ + + template_name = 'conntrackt/search.html' + + # Required permissions. + permissions = { + "all": ("conntrackt.view",), + } + + # Raise authorisation denied exception for unmet permissions. + raise_exception = True + + def get_context_data(self, **kwargs): + """ + Returns the context data that should be used for rendering of the + template. + + Adds context objects: + - 'entities', which is a list of entities that had the search term in + their name or description. + - 'projects', which is a list of entities that had the search term in + their name or description. + - 'search_term', which is a string of previous query that brought the + user to page (if any). The term will be stripped from leading and + trailing spaces/tabs. + """ + + # Set the context using the parent aclass. + context = super(SearchView, self).get_context_data(**kwargs) + + # Retrieve the search term, and strip it if it was provided. + search_term = self.request.GET.get("q", None) + if search_term: + search_term = search_term.strip() + + # Do not allow empty searches. + if search_term == "": + messages.error(self.request, "Search query is not allowed to be empty.", extra_tags="alert alert-error") + # Set-up the context objects if search was sent. Otherwise empty search + # page will be shown. + elif search_term is not None: + context['search_term'] = search_term + context['entities'] = Entity.objects.search(search_term) + context['projects'] = Project.objects.search(search_term) + + return context