Paul R
Paul R

Reputation: 2797

Use text both as Safetext and in url in Django

Suppose I want to convert the string [[w'ord]] into the link <a href="example.com?q=w'ord">w'ord</a>

Since input can be anything, I want to make it safe by applying conditional_escape (so, before making link I apply conditional_escape and string becomes [[w&#39;ord]]).

But in this case ' becomes unapplicable for the link because of the ampersand.

How can make the word safe for the html output and safe in the link?

Thank you.

Upvotes: 1

Views: 211

Answers (1)

Selcuk
Selcuk

Reputation: 59415

You must use django.utils.http.urlquote for the URL and django.utils.html.conditional_escape for the link text:

>>> from django.utils.http import urlquote
>>> from django.utils.html import conditional_escape
>>> urlquote("w'ord")
'w%27ord'
>>> conditional_escape("w'ord")
'w&#39;ord'

Upvotes: 1

Related Questions