简体   繁体   中英

Django static files when locally developing - how to serve absolutely?

This should be super simple, but somehow its has had me stuck all morning. I'm developing locally, using the django debug server, and with this filestructure:

/project/ (django project)
/static/ (static files)

In the settings.py MEDIA_ROOT and MEDIA_URL are both set to '/static/' and I'm using this in my urls.py

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

In my templates, the files that need to be server from the static directory are configured as such:

<link rel="stylesheet" href="{{ STATIC_URL }}css/style.css">

That all works as it should - the javascript/css/images are all served properly from the hompage. However, when I go to a subdirectory, such as http://127.0.0.1:8000/news/ then all the links are broken.

I've tried using a variety of the os.import options to get it to do the relative links properly, but havent had any luck. Is there a way that I could force it to be relative to the base url, or perhaps hardcode it to my filesystem?

Any help would be amazing!

I just had the same problem, and I solved it by removing first slash from STATIC_URL='/static/' and making it STATIC_URL = 'static/' just like philipbe wrote above. Wierd thing is that '/media/' works fine for MEDIA_URL at the same time (while 'media/' breaks layout).

Anyway - just change STATIC_URL to be equal to 'static/' with no leading slash, and you'll solve it.

In this line in your urls.py file, the '../static' should be changed to an absolute directory. Try changing it and see what happens.

Your file:

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

Should look more like:

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

To give you an example, mine is set up a little differently, but I still use a full path.

Here's how mine is setup: in settings.py

STATIC_DOC_ROOT = '/Users/kylewpppd/Projects/Django/kl2011/assets/'

and in urls.py :

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

I'm serving my static files from 'localhost:8000/assets/' .

How do your links break when you go to a subdirectory? Can you explain that further please.

Does django 1.3 support some kind of strange relative url routing for static media?

If it can be served from the homepage but not others, doesn't that sound exactly like your STATIC_URL is a relative location?

What is your STATIC_URL ? It should be absolute and start with a slash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM