简体   繁体   中英

not getting results in django search

I created a simple django blog where i want to provide a search option. so , I tried and didnt even get any error.

but the problem is I didn't even get any search results too. its showing empty page even if there is a post related to that query. help me out guys.

Here my code goes......

views.py

class home_view(ListView):
    model = home_blog_model
    template_name = "home.html"
    context_object_name = "posts"
    paginate_by = 8
    ordering = ['-date']


def search(request):
    query = request.GET.get("key")

    if query:
        results = home_blog_model.objects.filter(Q(title__icontains=query))
    else:
        results = home_blog_model.objects.filter(status="Published")


    return render(request , "home.html" , {"query":query})

urls.py

from django.urls import path
from . import views
from django.contrib.auth.views import LoginView , LogoutView
urlpatterns = [

    path("" , views.home_view.as_view() , name="blog-home"),
    path("posts/<int:pk>/" , views.detail_view , name="detail"),
    path("admin/login/" , LoginView.as_view(template_name="admin-login.html") , name="admin-login"),
    path("admin/logout/" , LogoutView.as_view() , name="admin-logout"),
    path("admin/post/create/" , views.create_post_view , name="create_post"),
    path("post/search/" , views.search , name="search_post"),
]

models.py

from django.db import models

class home_blog_model(models.Model):
    title = models.CharField(max_length=100)
    summary = models.CharField(max_length=300)
    content = models.TextField()
    date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

home.html

<div align="right">
    <form class="form-group" method="GET" action="{% url 'search_post' %}">
        <input type="text" name="key" placeholder="search........" value="{{request.GET.key}}">
        <button class="btn" type="submit">Search</button>
    </form>
</div>

thanks in advance !

You're not returning the results from the search view. The context you pass only contains the query.

Also, in home.html you're not iterating over the results, in an attempt to display them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM