Home > OS >  How to pre format a string to show hyperlink in frontend using django
How to pre format a string to show hyperlink in frontend using django

Time:12-04

I have a model in which I accept string data in the char field. this is populated through Django admin field.

Models.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})

my template which has html

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

this mock response of data:

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

how to show this as a link inside the paragraph in the front end.

the link might be present anywhere positioned in the paragraph as entered by the text in django-admin

currently the whole anchor tag is displayed instead of link

CodePudding user response:

Your question is not clear enough.

However. For links, you can use URLField instead of CharField.

To converts URLs and email addresses in text.

If you are not sure where the link might be in the text, you should use RegEx:

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"
  • Related