Django: How Add Static Files

2019-05-30 18:11发布

问题:

Readed all these topic https://stackoverflow.com/search?q=django.views.static.serve And it not helped :(

OS: Windows XP Python: 2.7 Django: 1.2.3

Media in
D:\bugtracker\static

With files:
docicons-note.gif
style.css

In settings.py i set:
MEDIA_ROOT = 'D:/bugtracker/static/'
MEDIA_URL = '/static/'

In urls.py i set:

urlpatterns = patterns('',
    (r'^media/(?P.*)$', 'django.views.static.serve',{'document_root':'settings.MEDIA_ROOT'}),
)

template: (read it without space in < tag>)
< !DOCTYPE html> < html lang='ru'>
< head>
< link rel="stylesheet" type="text/css" href="media/style.css" />
< /head>
< body>
< img src="{{MEDIA_URL}}/docicons-note.gif"/>
< /body>
< /html>

回答1:

urls.py:

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

settings.py MEDIA_ROOT = 'path/to/media/folder/'

So if you have /test_media/photo.jpg will be used the value from MEDIA_ROOT: 'path/to/media/folder/photo.jpg'

template file:

< !DOCTYPE html> < html lang='ru'>
< head>
< link rel="stylesheet" type="text/css" href="/test_media/style.css" />
< /head>
< body>
< img src="/test_media/docicons-note.gif"/>
< /body>
< /html> 

This should be used only for development purposes. For production you should use a real web server.



回答2:

Your settings.py has:

MEDIA_URL = '/static/'

But in urls.py your static serve app is pointing to "media". Change your static serve entry in urls.py to match the MEDIA_URL setting:

urlpatterns = patterns('',
    (r'^static/(?P.*)$', 'django.views.static.serve',{'document_root':'settings.MEDIA_ROOT'}),
)

Hopefully that works better for you.



回答3:

Static serving is only done via Django if the test server is running. If you're using a separate web server then you need to use that web server's facilities for serving static files, e.g. the Alias directive.