class PostList(ListView): template_name = 'posts/index.html' context_object_name = 'latest_posts_list' model = Post form_class_search = SearchForm paginate_by = 8 def get_queryset(self): if self.q: return Post.objects.filter( Q(description__contains=self.q) | Q(title__contains=self.q)).order_by(self.order) return Post.objects.select_related('user')\ .annotate(comment_count=models.Count('post_comments'))\ .order_by(self.order) def dispatch(self, request, *args, **kwargs): self.order = kwargs.get('order') self.q = "" self.search_placeholder = "search" self.search_form = SearchForm(request.GET or None) if self.search_form.is_valid(): self.q = self.search_form.cleaned_data['q'] self.search_placeholder = self.q return super(PostList, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(PostList, self).get_context_data(**kwargs) context['search_placeholder'] = self.search_placeholder return context
def post(self, request): form = SearchForm(request.POST) if form.is_valid(): q = form.cleaned_data['q'] posts = Post.objects.filter(text__icontains=q) context = {'q' : q, 'posts' : posts} return_str = render_to_string ('part_views/_post_search.html', context) return HttpResponse(json.dumps(return_str), content_type='application/json') else: HttpResponseRedirect("/search/")
def search(request): first_date = Post.objects.order_by('created')[0] posts = [] form = SearchForm() if request.method == 'POST': # If the form has been submitted... form = SearchForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass name = form.cleaned_data['name'] start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] search_comments = form.cleaned_data['search_comments'] search_term = form.cleaned_data['search_term'] entries = form.cleaned_data['entries'] query = Post.objects.all() if not search_comments: query = query.filter(parent__exact=0) if start_date: query = query.filter(created__gte=start_date) if end_date: query = query.filter(created__lte=(end_date + timedelta(days=1))) if name: query = query.filter(name__name__exact=name) if search_term: query = query.filter(message__icontains=search_term) posts = [] parent_ids = [] for item in query: if item.parent in parent_ids or item.p_id in parent_ids: pass elif item.parent == u'0': parent_ids.append(item.p_id) else: parent_ids.append(item.parent) posts = generate_posts(parent_ids[:int(entries)]) return render_to_response('posts/search.html', {'first_date' : first_date, 'form' : form, 'posts' : posts}, context_instance=RequestContext(request))