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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With