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

问题:

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?


回答1:

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://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.


回答2:

Some other thread

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.

  • 发表于 2018-07-10 14:18
  • 阅读 ( 279 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除