【问题标题】:How to pre format a string to show hyperlink in frontend using django如何使用 django 预先格式化字符串以在前端显示超链接
【发布时间】:2022-01-09 16:06:29
【问题描述】:

我有一个模型,我在 char 字段中接受字符串数据。这是通过 Django 管理字段填充的。

模型.py

class Test(models.Model):
   overview = models.CharField(max_length=10000, null=True, blank=False)

views.py

from .models import Test
def testView(request):
    data = Test.objects.all()
    return render(request, 'abc.html', {'data': data})

我的模板有 html

<p style="text-align: center; color: black">{{data.overview  | linebreaks}}</p>

这个数据的模拟响应:

"with the great power comes the great responsibility.
<a href="https://www.google.co.in/">connect</a>" from backend.

如何将其显示为前端段落内的链接。

链接可能出现在段落中的任何位置,如 django-admin 中的文本输入的那样

目前显示的是整个锚标签而不是链接

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    你的问题不够清楚。

    但是。对于链接,您可以使用URLField 而不是CharField

    To converts URLs and email addresses in text.

    如果您不确定链接在文本中的位置,您应该使用正则表达式:

    url_re = re.compile(r'^www.[a-zA-z$#./?=:;+&@{}|,%<>~0-9]*', re.IGNORECASE)
    words = word_split_re.split(str(text))
    
    for i, word in enumerate(words):
        if '.' in word or '@' in word or ':' in word:
            lead, middle, trail = '', word, ''
            lead, middle, trail = trim_punctuation(lead, middle, trail
    
        if url_re.match(middle):
                    url = smart_urlquote('http://%s' % html.unescape(middle))
                    klass = "js-css-class"
    

    【讨论】:

    • 不,我不想在模型中使用 URL 字段。有时链接可能会或可能不会出现在段落中的特定位置。所以我试图在将数据摄取到 char 字段中时预先格式化自己
    猜你喜欢
    • 1970-01-01
    • 2012-05-12
    • 2011-07-12
    • 2019-08-06
    • 2014-10-24
    • 2021-11-28
    • 2018-06-21
    • 1970-01-01
    • 2019-12-21
    相关资源
    最近更新 更多