Reputation: 2189
I want something similar to Twitter mentions that are turned into links but it is not working.
If we assume we have message
= 'Do not forget to come with the Python book, @friend'
#function to convert @mentions to links
def mentions(message, username):
this_user_handle = reverse('mysite:profile', args=[username])
new_message = re.sub(r'(@\w+)', r"<a href= '#'>\g<0></a>", message)
new_message.replace('#', this_user_handle)
return new_message
mentions(message, 'yax')
returns Do not forget to come with the Python book, <a href= '#'>@friend</a>'
.
The #
is not replaced and the new_message
still displays as is in HTML page:
<p class= 'Post'>
{{ new_message|linebreaksbr}}
</p>
This displays this:
Do not forget to come with the Python book, <a href= '#'>@friend</a>'
Instead of:
Do not forget to come with the Python book, @friend
How do I get around this? Thank you in advance!
Upvotes: 1
Views: 109
Reputation: 1088
Replace returns a new string.
new_message = new_message.replace("#", "...")
Also Django automatically escapes HTML in templates, to disable it use the safe filter.
Upvotes: 2
Reputation: 599620
The content is being automatically escaped to prevent things like script injection. Use the |safe
filter is you're certain that it can't contain anything nasty.
Upvotes: 1
Reputation: 2089
Use kwargs instead of args:
reverse('profile', kwargs={'user_name': username})
You should replace the href='' by href="" to avoid mixing things you don't want to mix (you would need to replace that in several places tho).
Upvotes: 0