最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make links clickable in my Django TextField - Stack Overflow

programmeradmin2浏览0评论

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, 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?

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?

Share Improve this question asked Jul 9, 2018 at 10:55 ZorganZorgan 9,12331 gold badges119 silver badges236 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 24

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.

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.

发布评论

评论列表(0)

  1. 暂无评论