Dastan Alymbekov
Dastan Alymbekov

Reputation: 11

How to use a variable inside quotes in a template? (Django)

I would like to change the photo on the sliders and for this I created the SliderImage model, in index.html I want to pull out the pictures using a loop, but it uses an unfamiliar tag for me and tried to pass the variable in quotes inside STATIC, but to no avail, I get this

/static/%7B%7B%20slider.get_absolute_image_url%20%7D%7D" style="background-image: url("/static/%7B%7B%20slider.get_absolute_image_url%20%7D%7D");">

index.html

{% for slider in slider %}
    <div class="hs-item set-bg" data-setbg="{% static '{{ slider.get_absolute_image_url }}' %}">
        <div class="container">
            <div class="row">
                <div class="col-xl-6 col-lg-7 text-white">
                    <span>New Arrivals</span>
                    <h2>denim jackets</h2>
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quis ipsum sus-pendisse ultrices gravida. Risus commodo viverra maecenas accumsan lacus vel facilisis. </p>
                    <a href="#" class="site-btn sb-line">DISCOVER</a>
                    <a href="#" class="site-btn sb-white">ADD TO CART</a>
                </div>
            </div>
            <div class="offer-card text-white">
                <span>from</span>
                <h2>$29</h2>
                <p>SHOP NOW</p>
            </div>
        </div>
    </div>
{% endfor %}

models.py

from django.conf import settings
from django.db import models

class SliderImage(models.Model):
    img = models.ImageField(upload_to='media/slider_photo/', verbose_name='Photo')
    @property
    def get_absolute_image_url(self):
        return "{0}{1}".format(settings.MEDIA_URL, self.img.url)

    def __str__(self):
        return "{}".format(self.img)

views.py

def index(request):
    slider = SliderImage.objects.all()
    return render(request, 'main/index.html', {'slider': slider})

Upvotes: 1

Views: 912

Answers (2)

Lord Elrond
Lord Elrond

Reputation: 16032

You shouldn't use {{ inside of {% blocks. So in your case:

data-setbg="{% static slider.get_absolute_image_url %}">

But that probably won't work because get_absolute_url typically returns the absolute url, which means that you shouldn't use static here:

data-setbg="{{ slider.get_absolute_image_url }}">

Upvotes: 1

Nad
Nad

Reputation: 556

You are uploading the image in a media folder and not to static. In your index.html it should be instead:

data-setbg="{{ slider.get_absolute_image_url }}">

Upvotes: 0

Related Questions