Search code examples
djangotemplatesurlhref

django URL in a TextField with HTML


In my Django e-commerce project, I have an obvious Product model with an expected description field:

description = models.TextField(...)

I have the following url configured:

path("product/slug:slug", views.product_detail, name="product_detail"),

which, obviously, serves URLs like this:

http://localhost:8000/product/foo

and when a product foo is a part of a set with product bar, I want to add respective links to the description field on such products, like "you might want to buy bar together with this".

However, adding a link to bar to the description of foo proved tricky. The whole description field (imported from a legacy ecomm app) can contain arbitrary HTML, and since it's not a user input, I render it like this in the template:

{% autoescape off %}
  {{ product.description }}
{% endautoescape %}

When I add this to the (TextField) description:

> This item together with <a href="product/bar">Bar</a> (sold separately)

, the URL produced in the template is wrong:

http://localhost:8000/product/product/bar/

, but if I don't use this '/product' in the description's url:

> This item together with <a href="/bar">Bar</a> (sold separately)

, the URL is also wrong:

http://localhost:8000/bar/

I'll admit, I don't understand how Django constructed the first or second URL. So it's ironic that neither is what I want )

Thank you for your time.


Solution

  • This is not related to Django. Try to use

        > This item together with <a href="/product/bar">Bar</a> (sold separately)
    

    Notice the link starts with a slash

    Hope it helps