Home > Mobile >  How do you add a link in an f string?
How do you add a link in an f string?

Time:10-16

I am trying to add a link in the f string below:

d  = f'<li> {event.time} {event.teacher} {event.student} {event.status} </li>'

Basically, I want it to look something like below:

f'<li> <a href="{% url 'somewhere' event.pk %}"> {event.time} {event.teacher} {event.student} {event.status} </a> </li>'

However, I get the following error when I do this:

SyntaxError: f-string: expecting '}'

Do you guys know how to input a link in an f string? Please ask me any questions you have.

Here is the context of the code where I have the f-string as some of you asked:

class Calendar(HTMLCalendar):
    def __init__(self, year=None, month=None):
        self.year = year
        self.month = month
        super(Calendar, self).__init__()

    # formats a day as a td
    # filter events by day
    def formatday(self, day, events):
        events_per_day = events.filter(date__day=day)
        d = ''
        if True:
            for event in events_per_day:
                d  = f'<li> {event.time} {event.teacher} {event.student} {event.status} </li>'

        if day != 0:
            return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>"
        return '<td></td>'

By the way, this is all in my utils.py folder.

CodePudding user response:

An f-string does will not evaluate Django template tags, it just sees this as curly brackets, but where the content happens to be a non-sensical expression.

You can make use of reverse(…) [Django-doc] to perform URL pattern resolution:

from django.urls import reverse

f'<li> <a href="{ reverse("somewhere", args=(event.pk,)) }"> {event.time} {event.teacher} {event.student} {event.status} </a> </li>'

CodePudding user response:

you can use variable to achieve the same output :-

url_endpoint = reverse("somewhere", args=(event.pk,))

f'<li> <a href="{url_endpoint}"> {event.time} {event.teacher} {event.student} {event.status} </a> </li>'
  • Related