Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

how to implement search that can access complete database in Django

My views.py

class SearchView(TemplateView):
    template_name = 'search.html'

    def get(self, request, *args, **kwargs):
        q = request.GET.get('q', '')
        self.results = Item.objects.filter(title__icontains=q)
        return super().get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        return super().get_context_data(results=self.results, **kwargs)

My urls.py

url(r'^search/$', SearchView.as_view(), name='search')

My search.html

{% extends 'base.html' %} {% load static %} {% block content %}

<body>
    <h1>Search Result</h1>
    <ul>
        {% for item in q %}
        <li>
            {{ q.title }}, {{ q.price }}
        </li>
        {% endfor %}
    </ul>

</body>
{% endblock%}}

My nav.html

<form method="GET" action="{% url 'core:search' %}">

This is the code that i used but due to some missing or error in this above code i can't get any data if i make any search in my website, Can some one please tell me what is the mistake i have done. Thank you.

My Models.py

class Item(models.Model):
    title = models.CharField(max_length=50)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    model_no = models.CharField(max_length=100)
question from:https://stackoverflow.com/questions/65932614/how-to-implement-search-that-can-access-complete-database-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try this:

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context['results'] = self.results
        return context

in html

{% extends 'base.html' %} 
{% load static %} 

{% block content %}

<body>
    <h1>Search Result</h1>
    <ul>
        {% for item in results %}
        <li>
            {{ item.title }}, {{ item.price }}
        </li>
        {% endfor %}
    </ul>

</body>
{% endblock%}}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...