I have below function in my views.py Django 2 project and I am trying to pass the variable "stylefolder" from views.py to my base.html template in order to dynamically get the correct href in my link tag.
Below is my current code:
def home(request):
products = Product.objects.order_by('-votes_total')
paginator = Paginator(products, 10)
page = request.GET.get('page')
paged_listings = paginator.get_page(page)
context = {
'products':paged_listings,
'stylefolder': 'cryptoblog/style.css'
}
return render(request,'home1.html', context)
In the base.html file, I have below code.
href="{% static '{{ stylefolder }}' %}">
The problem is that when I look into the view:Source section of the page, I get as a result:
<link rel="stylesheet" type="text/css" href="/static/%7B%7B%20stylefolder%20%7D%7D">
instead of below desired result:
<link rel="stylesheet" type="text/css" href="/static/cryptoblog/style.css">
What should I change to get "/static/cryptoblog/style.css" in the href tag?
Since you are in a template tag, you should not add the double curly brackets {{ .. }}
, you can use the variablename instead, like:
<link href="{% static stylefolder %}" rel="stylesheet" type="text/css"">
The reason why you get /static/%7B%7B%20stylefolder%20%7D%7D
is because this is the percent-encoding [wiki] of the '{{ stylefolder }}'
string. This is logical, since it looks like you passed a string literal:
>>> from urllib.parse import unquote
>>> unquote('/static/%7B%7B%20stylefolder%20%7D%7D')
'/static/{{ stylefolder }}'
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments