Reputation: 1270
I am building a small and simple Question and Answer Web App and I am trying to implement a search page.
When i search question title than results are showing fine below the search field.
BUT I am trying to show the answers of the searched tag on another page.
models.py
class Questions(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=30,default='')
tags = TaggableManager()
class Answers(models.Model):
quest = models.ForeignKey(Questions,on_delete=models.CASCADE)
views.py
def search(request):
query = request.GET.get('q')
if query:
objs = Questions.objects.filter(tags__name__icontains=query)
context = {'objs': objs}
return render(request, 'search.html', context)
search.html
{% for qas in objs %}
{{ qas.title }}
{% endfor %}
{% for ans in answer %}
{{ ans.ans }}
{% endfor %}
This view is showing answers in single page ( In searched pages ).
I will appreciate your Help. Thank You in Advance
Upvotes: 0
Views: 56
Reputation: 2692
First of all, you need to add query to context of search
view to link corresponding answers:
def search(request):
...
context = {'objs': objs,'query':query}
return render(request, 'search.html', context)
Then you can create search_answer
view, pass query as an argument and filter Answer
model according to that query:
def search_answer(request, query):
if query:
answers = Answers.objects.filter(quest__tags__name__icontains=query)
context = {'answers': answers}
return render(request, 'search_answer.html', context)
Update urls file to pass query:
urlpatterns = [
path('answers/<query>', search_answer, name='search-answer'),
]
In search.html
you can link to answers page as follows:
<form action="{% url 'search' %}" method="get">
<input name="q" type="text">
{% for qas in objs %}
{{ qas.title }}
{% endfor %}
<a href="{% url 'search-answer' query=query %}">See answers</a>
</form>
Finally in search_answer.html
, you can show answers with something like this:
{% for answer in answers %}
Question: {{ answer.quest.title }}
Answer: {{ answer.body }}
{% endfor %}
Upvotes: 2