0

I have six images name as 1.jpg to 6.jpg of each side of dice and I want to display image defined by a random number I generate in runtime.

How can I make dynamic path including this random number? I tried some ways but getting 404 image not found only.

settings.py

STATIC_URL = '/static/'

Folder with images:

D:\programs\Django_projects\src\dice\random_dice\static\images

Dice is my project name and random_dice is my app name.

I already tried this:

<img class="myImage" src='{% static "images/{{ number }}.jpg"%}' alt="can not load the image">

and

<img class="myImage" style="background-image:url('{{ STATIC_URL }} images/{{ number }}.jpg')" alt="can not load the image">

Also tried before the rendering page to make custom name and put in dict but still not working

view.py

def home(request):
   X = random.randrange(1, 6)
   result = {
   "number": X,
   "myImage": str(X) + '.jpg'
   }
   return rander(request, 'home.html', result)

In that condition ...

<img class="myImage" src='{% static "images/{{ myImage }}"%}' alt="can not load the image">

And

<img class="myImage" style="background-image:url('{{ STATIC_URL }} images/{{ myImage }}')" alt="can not load the image">

Should I move image folder to else position or change STATIC_URL or the syntax is wronge? I have no idea please help.

1
  • try moving the static folder inside dice so your path should look like D:\programs\Django_projects\src\dice\static Commented Mar 23, 2021 at 9:40

1 Answer 1

1

One of possible solutions:

<img class="myImage" src='{% static "images" %}{{ myImage }}' />

static "images" will prepend "images" with STATIC_URL, myImage was taken outside of {% %} and now double curly braces work fine.

Sign up to request clarification or add additional context in comments.

Comments

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.