Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a python list of URLs to a Django template and make them clickable?

Tags:

python

django

I have a python list of urls which looks like this:

list = ['/abc/1', 
       '/abc/3',
       '/abc/5',
       ...
       ]

all these urls follow the url pattern 'abc/n/' which I have defined in urls.py. now I want to pass this list to a django template in such a way that each element of this list becomes clickable and runs the function corresponding to their url pattern on clicking them. I tried hardcoding the anchor tag to each element of this list. for example

for i in range (len(list)):    
    list[i] = "<a href = \'" + list[i] + "\'>click me</a>"

and then sending this list to template via HttpResponse() function via a context. But this displayed the list items in raw text format instead of links

like image 288
Tarun Khare Avatar asked Dec 23 '22 08:12

Tarun Khare


1 Answers

What is happening here is that django is being safe and escaping your html. This is to prevent XSS vunerabilities. This is a vulnerability that happens when e.g. users can insert malicious HTML into your site.

Now, you could turn that off, but then you risk having the aforementioned security issues.

What you will want to do instead is generate the html in the template, not in your code (that's what templates are there for):

{% for link in links %}
<a href="{{ link }}">click me</a>
{% endfor %}

Now you just need to pass links in your template context!

like image 182
Azsgy Avatar answered Apr 29 '23 18:04

Azsgy