Having trouble Fetching Search Results

So i was following the awesome tutorial here with few customization of my own,

but the search results dont show anything and also with no errors . Please Help

My Urls File

from django.urls import path

from . import views

from .views import HomePageView, home, SearchResultsView

urlpatterns = [
path(‘home’, home, name = ‘home’),
path(‘posts’, HomePageView.as_view() , name = ’ Post’),
path(‘search/’, SearchResultsView.as_view(), name=‘search_results’),

My Views File:

from django.shortcuts import render

from django.views.generic import ListView

from .models import Post

from django.db.models import Q

Create your views here.

def home(request):
return render(request,‘blog/home.html’)

class HomePageView(ListView):
model = Post
template_name = ‘blog/post.html’

class SearchResultsView(ListView):
model = Post
template_name = ‘blog/search_results.html’

def get_queryset(self):
  query = self.request.GET.get('q')

  if query :
  	object_list = Post.objects.filter(title__icontains=query) 
  	return object_list 

  	query = ""

my Models File:

from django.db import models

from django.utils import timezone

from django.contrib.auth.models import User

Create your models here.

class Post(models.Model):
title = models.TextField()
image = models.ImageField(upload_to=‘images/’)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)

def __str__(self):
	return self.title

My Search Html Template:

{% extends ‘blog/base.html’ %}

{% block content %}

Search Results

{% csrf_token %}

{% endblock content %}

First, a side note. When posting code, please enclose the code between lines consisting of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This allows the forum software to keep your code properly formatted, which is essential with Python. (You can also edit your original post to put the ``` before and after the code you originally posted.)

I’m not sure if this is an artifact of the code being mangled by the forum software, but I don’t see where you’re rendering your search results in your template.

Also, get_queryset is supposed to return a queryset, not a string. When there’s no query defined, you want get_queryset to return a queryset that returns no data.

1 Like

oh crap i was not rendering it to show results in my template , thanks a lot
silly mistake by me

you are awesome. keep up the good work. we need more ppl like you :slight_smile: