1

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!

1
  • 1
    Try safe Commented Oct 21, 2014 at 15:29

3 Answers 3

2

Replace returns a new string.

new_message = new_message.replace("#", "...")

Also Django automatically escapes HTML in templates, to disable it use the safe filter.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Anything nasty? Can you enlighten me more on that? Links can do.
User handler or message containing <script>alert("I'm nasty");</script> for example.
0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.