Home > Software design >  Changing an image name in django
Changing an image name in django

Time:05-29

So I have 5 images as static files and I want to randomly select an image to display when I press a button. I'm having problems with getting the imagename update. When I hard code the name into html it does work.

In my views I have:

def test(request):
    imagename = 'img'   str(random.randint(0,5))   '.jpeg' #all the images end with jpeg so this can't be the problem
    print(imagename)
    return render(request, 'mainbook/index.html', {'image': imagename})

In urls.py I have

urlpatterns = [path('test/', views.test, name='test')]

And finally in index.html I have:

<form method="post" action="{% url 'mainbook:test' %}">
    {% csrf_token %}
    <button id="button">Press here</button>
</form>
<img src="{% static '/mainbook/images/{{image}}' %}"></img>

This is of course a simplified version but I do think the problem is somewhere in this code. I just don't know where exactly.

CodePudding user response:

You are trying to close an img tag, and you can't use "{{ }}" inside "{% %}"

From:

<img src="{% static '/mainbook/images/{{image}}' %}"></img>

To:

<img src="{% static '/mainbook/images/{{image}}' %}">

Then:

<img src="{% static '/mainbook/images/{{image}}' %}">

To:

<img src="{% static '/mainbook/images/' %}{{image}}">

Should work.

  • Related