Django static files in local development - how to serve absolutely?

It should be very simple, but somehow it made me stuck all morning. I am developing locally using the django debug server, and with this structure:

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

In settings.py, MEDIA_ROOT and MEDIA_URL are both set to '/ static /' and I use this in my urls.py

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

In my templates, files that should be a server from a static directory are configured as such:

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

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

I tried using various os.import options to make it relate to links correctly, but havent been lucky. Is there a way that I could make it relate to the base url, or maybe hard-link it to my file system?

Any help would be awesome!

+4
source share
3 answers

In this line in your urls.py file '../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'}),

It should look bigger:

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

To give an example, mine is set up a little differently, but I'm still using the full path.

Here, as my 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 serve my static files with 'localhost:8000/assets/' .

+1
source

I had the same problem and solved it with the help of removing the first slash from STATIC_URL = '/ static /' and making it STATIC_URL = 'static /' just like philipbe wrote above. Moreover, "/ media /" works fine for MEDIA_URL at the same time (while "media /" breaks the layout).

In any case, just change STATIC_URL to "static /" without a leading slash, and you will solve it.

+1
source

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

Does django 1.3 support some kind of weird relative URL routing for static media?

If this can be served from the homepage but not with others, does it not look like your STATIC_URL is a relative location?

What is your STATIC_URL ? It must be absolute and begin with a slash.

0
source

Source: https://habr.com/ru/post/1340255/


All Articles