I'm trying to make a search bar in Django that searches for pages by displaying the name and url of the page.
Right now, I can only display the url of a page as plain text when it gets searched.
I want the url to be a clickable link that leads to the page.
**This is what my code looks like currently: ** The search results page search_page.html:
{% extends 'contents/main.html' %}
{% block content %}
<center>
{% if searched %}
<h1>You searched for {{searched}}</h1>
<br/>
{% for page in pages %}
{{ page }} - {{page.web}}<br/> <!-- page displays name of page and page.web displays url as text -->
{% endfor %}
{% else %}
<h1>You forgot to search for a page</h1>
{% endif %}
</center>
{% endblock content %}
The method for search_page.html in views.py:
def search_page(request):
if request.method == 'POST':
searched = request.POST['searched']
pages = Pages.objects.filter(name__contains=searched)
return render(request, 'contents/search_page.html', {'searched':searched, 'pages':pages })
The models.py class for pages:
class Pages(models.Model):
name = models.CharField('Page Name', max_length=120)
web = models.URLField('Page URL') <!-- this gets the url of the page -->
def __str__(self):
return self.name
**WHAT I'VE TRIED **
I've tried turning page.web into a url but it gave me a TemplateSyntaxError:
<br/> {% for page in pages %} {{ page }} - {{% url 'page.web'%}}<br/>
If page.web
variable contain url that generated from route name specified in urls.py file then in html you need to specify like the following to make the page as hyperlink
{% for page in pages %}
<a href="{% url page.web %}"> {{ page }} </a><br/>
{% endfor %}
If you have an absolute url
in the page.web
then you may rewrite the hyperlink as follows.
<a href="{{ page.web }}"> {{ page }} </a><br/>