Reputation: 9153
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?
Upvotes: 8
Views: 5360
Reputation: 477308
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://
, orwww.
. For example,https://goo.gl/aia1t
will get converted butgoo.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.
Upvotes: 24
Reputation: 126
Django has the urlize template filter which will automatically detect both URLs and email addresses and turn them into the appropriate hyperlinks.
The docs there are actually a little thin, so I recommend also reading the docstring in the source for the urlize function for more information.
Upvotes: 1