0
votes

I came from PHP, Python and Django are new to me. I have a simple problem but have already stuck with this for hours and still couldn't find out what went wrong.

I want to insert a simple image into the template.

I have followed TemplateSyntaxError 'staticfiles' is not a valid tag library' and https://docs.djangoproject.com/en/1.3/howto/static-files/#with-a-template-tag

Following are my settings.

  1. my static folder is located in /myproject/myapp/static/. And the img path is /static/images/hi.jpg.
  2. the src value in img tag is "/static/images/hi.jpg" when the page is rendered
  3. Setting in setting.py

    STATIC_URL = '/static/'    
    INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    'django.contrib.admin')

  1. In template, I have

    
     {% load static %}
     {% get_static_prefix as STATIC_PREFIX %}
    
    

    and the source part of the image

    
    

    src="{{ STATIC_PREFIX }}images/hi.jpg"

  1. finally, the url of the app is http://127.0.0.1:8000/myapp/

what part is wrongly configured? Any idea? Thank you so much for the help. Sorry for the poor formatting.

2

2 Answers

1
votes

I use in html {% load staticfiles %} and e.g.

<img src="/static/images/loader.gif" alt="loader.gif"></img>

or also

<img src="{% static 'images/loader.gif %}" alt="loader.gif"></img>

with setting.py

BASE_DIR = os.path.dirname(os.path.dirname(__file__))    

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

STATIC_URL = '/static/'

and it works (Django 1.7 and Python3.4).

0
votes

In your urls.py you should add the static files urls:

# urls.py

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = patterns('',
    ...
)

urlpatterns += staticfiles_urlpatterns()