Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make links clickable in my Django TextField

I have a Textfield like so:

class Comment(models.Model):
    ...
    comment_text = models.TextField(max_length=650, blank=True, null=True)

When someone posts a link in the TextField, e.g. www.stackoverflow.com, I want it to be clickable (nested in an <a> tag). Is there any way to do this with code and not using a text editor?

like image 701
Zorgan Avatar asked Jul 09 '18 10:07

Zorgan


1 Answers

You can use the urlize [Django-doc] template filter tag for this. So instead of writing:

{{ some_comment.comment_text }}

you should write:

{{ some_comment.comment_text|urlize }}

According to the documentation, we then get:

Converts URLs and email addresses in text into clickable links.

This template tag works on links prefixed with http://, https://, or www.. For example, https&colon;//goo.gl/aia1t will get converted but goo.gl/aia1t won’t.

It also supports domain-only links ending in one of the original top level domains (.com, .edu, .gov, .int, .mil, .net, and .org). For example, djangoproject.com gets converted.

(..)

If value is "Check out www.djangoproject.com", the output will be "Check out <a href="http://www.djangoproject.com" rel="nofollow">www.djangoproject.com</a>".

A related template filter is urlizetrunc [Django-doc] where the links are not only clicable, but truncated as well. For example:

{{ some_comment.comment_text|urlizetrunc:15 }}

In that case the URLs the user sees (of course not the link itself) is truncated to 15 characters, since links can be quite long and chaotic.

like image 126
Willem Van Onsem Avatar answered Sep 30 '22 13:09

Willem Van Onsem