0
votes

I am following the Django 1.6 tutorial on how to work with static files (https://docs.djangoproject.com/en/1.6/howto/static-files/). However, something is not working...

This is what I have so far...

URLS:

#mysite/urls.py:

from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^myapp/', include('myapp.urls')),
)

#mysite/myapp/urls.py:

from django.conf.urls import patterns, include, url
from myapp import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
)

VIEWS:

#mysite/myapp/views.py:

from django.shortcuts import render
def index(request):
    return render(request, 'myapp/index.html')

TEMPLATES:

#mysite/myapp/templates/myapp/index.html:

{% load staticfiles %}
<img src="{% static "myapp/image1.jpg" %}" alt="Image 1"/>

In the mysite/settings.py file, I have STATIC_URL = '/static/'. In the folder mysite/myapp/static/myapp, I have a file named image1.jpg.

When I run the development server, it runs fine if I just put some other HTML in my index.html file, but when I try to display the image as above, it just shows a little white box where the image should be. Furthermore, if I go to localhost:8000/myapp/static/myapp/image1.jpg, I get a 404 error.

I'm assuming I'm doing something very obviously wrong...but what is it?

One thing - the STATIC_URL in settings.py is relative to the app directory, not the project directory, right?

Thank you!

2
Are sure that you have set STATICFILES_DIRS right in your settings file ?Anup

2 Answers

1
votes

When you're running in production, your static files are managed by the server (Apache, nginx) however when your DEBUG is set to true in your settings.py you'll have to tell django to serve the static files for you. To do this add the following to your URLs.py:

from django.conf import settings

(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_ROOT}),

This will allow static to be searchable and serve your static files.

0
votes

img src="{% static 'myapp/image1.jpg' %}" alt="Image 1"/>