Search code examples
pythonhtmldjangofolium

Write the URL in a variable in the Django view


I want to put a link inside a variable (in View Django) But I get a error. In the slug section (slug =% slug), Python confuses % url with %u!

Error: %u format: a number is required, not str

I use the Folium library and want to put a link in the popup. So, I can not use the normal mode and I have to use another method.

for i in range(10):
    slug=i
    url = Template(
    """
    <!DOCTYPE html>
                <html>
                <body>
                    <a href="{% url 'test' slug= %slug %}" target="_blank" style=" text-align: 
   right; ">Mor Info</a>
                </body>
                </html>
    """%slug).render(Context({}))



popup = folium.features.GeoJsonPopup(
            fields=["name"],
            aliases=[f'{url}'],
            labels=True,
            localize=True,
            style="background-color: yellow;")

Solution

  • You already pass a empty context, use that instead of string formatting.

    for i in range(10):
        slug=i
        url = Template(
        """
        <!DOCTYPE html>
                    <html>
                    <body>
                        <a href="{% url 'test' slug=slug %}" target="_blank" style=" text-align: 
       right; ">Mor Info</a>
                    </body>
                    </html>
        """).render(Context({'slug': slug}))
    
    
       popup = folium.features.GeoJsonPopup(
                fields=["name"],
                aliases=[f'{url}'],
                labels=True,
                localize=True,
                style="background-color: yellow;")
    

    Or just write %s, instead of %slug, you're mixing things up I think.

    print("%s" % "1")
    print("%(bla)s" % {'bla':1})  # close to what you're attempting.
    foo=1
    print("{bla}".format(bla=1))
    print(f"{foo}")
    

    All print '1'.