Denys
Denys

Reputation: 4557

Link to a django static file doesnt work

In my dev. environment there is a /static/ folder, which atm. stores some images for the web-site.

  1. My INSTALLED_APPS variable in settings.py does contain the django.contrib.staticfiles app and

    STATIC_URL = '/static/'

    STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'),)

  2. My urlpatterns variable in urls.py has this

    urlpatterns+= static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

  3. Finally, in my template.html file i'm iterating through my cardset objects and am trying to provide an image for each object like this

    <img src=" {{STATIC_URL}}/images/{{cardset.image}}" alt="{{ cardset.name }}" class="bn"/>
    

Now, the problem is:

a.) the {{STATIC_URL}} resolves as an empty string.

b.) i think i cannot use the static tag here because the variable {{cardset.image}} would not work well inside of the django tamplate {% ... %} with the static tag.

Could you please advice on what I should try doing here?

Upvotes: 0

Views: 443

Answers (2)

DrBuck
DrBuck

Reputation: 952

It seems to me you can still use the static tag. To build your string without using an image field, your link just needs tweaking slightly:

<img src="{% static "images/" %}{{cardset.image}}" alt="{{ cardset.name }}" class="bn"/>

which should render in html correctly. Depending what your {{cardset.image}} looks like you may be able to get rid of the images/ part in the middle.

Remember you also need to include {% load staticfiles %} at the top of your template.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600026

Since cardset.image is a string, your assumption b is false; tags work perfectly well with variables:

 {% static cardset.image %}

(The reason {{ STATIC_URL }} wasn't working was presumably because you haven't passed it to the template; it's not present automatically, it's just a standard template variable.)

Upvotes: 0

Related Questions