1

I have a model called Post with a FileField which is an image.

I want to do something like this:

.article-image{
    background-image: url("../img/{{ post.postimage }});
}

but obviously it does not work, so I tried to make inline css instead:

<div class="article-image" style="background-image:{% static 'img/{{ post.postimage }}' %}"></div>

but it does not work too.

How can I fix this

1 Answer 1

1

for the first case you can't do that because it's CSS file not Django template. but for the second case, you can use template tags like this

create templatetags/my_custom_tag.py in your app and add the following code into it.

from django import template
from your_base_app.settings import STATIC_URL

register = template.Library()

@register.simple_tag
def show_image(img):
    return STATIC_URL + 'img/' + img;

you should load your tags in the top of your django template like that

{% load my_custom_tag %}

your django template should be like this

<div class="article-image" style="background-image:url({% show_image post.postimage.url %})"></div>
Sign up to request clarification or add additional context in comments.

6 Comments

don't forget to import STATIC_URL from your settings
my static url is /static/ so can I hard code it ? it never changes
what do you mean hard code it? do you mean like that style="background-image: /static/img/'{{ post.postimage }}' " ?
what is templatetags ? is it a file or a directory and where do I create it
it's directory, you should create it inside your app
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.