Serving static media during Django development: Why not MEDIA_ROOT? - python

I read this guide about serving static media with Django during development.
I noticed that MEDIA_URL and MEDIA_ROOT were not used in this. Why? What's the difference?
I tried doing it with MEDIA_URL and MEDIA_ROOT, and got weird results.

In a production situation you will want your media to be served from your front end web server (Apache, Nginx or the like) to avoid extra load on the Django/Python process. The MEDIA_URL and MEDIA_ROOT are usually used for this.
Running the built in Development server you will need to set the correct url in your url.py file - I normally use something like this:
from django.conf import settings
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
Which picks up the MEDIA_ROOT from your settings file meaning that it works for development and live.

Straight from the comments in settings.py...
MEDIA_ROOT
The MEDIA_ROOT is the absolute path to the directory that holds media such as /home/media/media.lawrence.com/.
MEDIA_URL
The MEDIA_URL is the URL that handles the media served from MEDIA_ROOT. Make sure to use a trailing slash if there is a path component (optional in other cases). Examples: "http://media.lawrence.com", "http://example.com/media/".
So, to reword those... The MEDIA_ROOT is where the files live physically on your system, and the MEDIA_URL is where those files are mapped to. In development, this might not always be accessible, and in most cases your dev environment and your production environment are not the same, and it is something you're going to have to go back and change. The other thing is that it is NOT A GOOD PRACTICE when Django was designed NOT to serve static content for you.
If you're going to use this in development, I suggest you use the method of limiting it to DEBUG=True. Telling Django to serve static content from a temporary location while in development when the DEBUG is set to True is a much better and safer practice. You're NOT going to put your site into production with DEBUG on, right? Well, at least you shouldn't.
Here is how I implemented it:
settings.py:
STATIC_DOC_ROOT = os.path.join(os.getcwd(), 'site_media')
urls.py:
from django.conf import settings
## debug stuff to serve static media
if settings.DEBUG:
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT}),
)
This way any project I'm working on has a site_media directory inside of it with all of the media necessary. In dev it is self-contained and I don't have to flip any bits in the settings except for DEBUG, which I would be doing anyways.

The Django docs recommend the following approach I've modified for my use case:
urlpatterns = [
# url patterns
]
from django.conf import settings
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Note: the above assumes you've set your MEDIA_URL and MEDIA_ROOT correctly
... and here's the djangodocs linkslap.

Related

Django admin: image saved but error occured when click

I am ashamed to ask a question of that sort but I still can not solve my problem. I normally uploaded image in my media directory and can see image link in my admin but if I click on link I get:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/photo/img/9.jpg
Using the URLconf defined in TeamStudy.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, photo/img/9.jpg, didn't match any of these.
my project structure:
src
static/
photo/
img/
settings:
PROJECT_DIR = os.path.dirname(os.path.dirname(__file__))
BASE_DIR = os.path.dirname(PROJECT_DIR)
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'photo')
MEDIA_URL = '/photo/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
STATIC_URL = '/static/'
urls.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
I suspect it perhaps quite simple and I miss something. Please point me.
You need to add the media MEDIA_ROOT and MEDIA_URL in your urlpatterns
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
check following links for more details
Accessing "Media" files in Django
Django classifies user files in two types
Static files
Media files
this link helps you understand the difference between them
Your issues deals with Media files.
In future development, you may need to serve static files, to serve them you will need to add
STATIC_ROOT and STATIC_URL to the urlpatterns in a similar way that MEDIA_ROOT and MEDIA_URL are added
Change your URL's patterns:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
for more info Django Docs
First point: don't put uploaded medias in you static directory - static is for static files that are part of your project (css, js etc) -, you want to use MEDIA_ROOT and MEDIA_URL for this.
wrt/ serving the static and media contents, it depends on the environment. On your local dev environment you want to use the staticfile.views to serve both static and medias as mentionned in the other answers, but don't do this in production : on a production server, you want to use your front web server to serve static (and media) contents.

Django Development - Admin CSS file 404

I'm using this guide to attempt to get this working. Basically, I'm exploring django 1.6 (with python 2.7.6 on Mac OS X Yosemite beta), still working with the stock development server. I'm trying to include a CSS file to override some styles in the admin area. I have a static folder in my project root. My settings.py is completely stock (that means I have DEBUG set to true and that I'm using django.contrib.staticfiles). Inspecting the source and request/response reveals that I'm calling for the CSS file at my expected path, but that I'm getting a 404 when attempting to load it. I also get a 404 when attempting to hit the CSS file directly in the browser. I've searched google and SO and have not, as of yet, been able to find an answer.
The requested CSS file:
http://*mysite*/static/admin/css/mysite-admin.css
The file system path to the CSS file:
*myprojectdir*/static/admin/css/mysite-admin.css
Yes it won't work because Django does not serve by default static assets, in order to have static assets served (mind though this should be the case only for local dev) in your main urls.py file add this to the top:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
And then at the end of your urls.py:
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', # NOQA
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
) + staticfiles_urlpatterns() + urlpatterns
Make sure you have defined STATIC_URL, MEDIA_ROOT and MEDIA_URL in your settings.py, for development STATIC_ROOT IS NOT needed.

Managing URLs in a Django site inside a folder

So I have my Django project in a folder on my server, like so:
www.mydomain.com/myfolder/
The index page loads, but things like the css document don't because the paths are improper. Am I missing a shortcut? I looked through the settings.py documentation for a place to specify my site folder, but didn't find anything to help.
So example, if I specify this in my settings:
STATIC_URL = 'static/'
Then it will look for my css doc on my /myfolder/login page at:
http://mydomain.com/myfolder/login/static/stylesheet.css
If I specify:
STATIC_URL = '/static/'
Then it will look for my css doc on my /myfolder/login page at:
http://mydomain.com/static/stylesheet.css
Meanwhile, my css document is at:
http://mydomain.com/myfolder/static/stylesheet.css
Do I need to change everything and specify /myfolder/ before everything?
I think you need to add path of you STATIC_ROOT in settings, and update urls.py file.
My example:
#settings.py
....
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static",)
#path to your static folder
#urls.py
...
from django.conf import settings
from django.conf.urls.static import static
....
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
This question has a good practice solution on django tutorial:
See:
https://docs.djangoproject.com/en/1.6/intro/tutorial06/#customize-your-app-s-look-and-feel
That you should create a /static/appname/ folder inside each of your app, and then put the static files inside it.
So in your app, the static file url should turned into something like:
http://mydomain.com/static/app_name/stylesheet.css
Which won't collides with other app.
You'd better read the link I offered above, the tutorial shows a good habit.
Don't you just need to do this?
STATIC_URL = '/myfolder/static/'

Django static files won't load

i'm a Django newbie working on my first project and having a problem with static files.
I have created a simple auth system using django.contrib.auth consisting of two templates: mysite/templates/index.html and mysite/templates/registration/login.html. I have global static content in mysite/static which I want to be able to access on all templates rendered by all apps.
mysite/templates/index.html contains <img src="{{ STATIC_URL }}pics03.jpg"/> which renders as "static/pics03.jpg" and loads fine when I visit the url localhost:8000/
mysite/templates/registration/login.html contains <img src="{{ STATIC_URL }}pics03.jpg"/> which also renders as "static/pics03.jpg" and does not load when I visit the url "localhost:8000/accounts/login/"
In my urls.py I have:
urlpatterns = patterns('',
url(r'^$', 'mysite.views.home'), # plays index.html template
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
In my settings.py I have:
PROJECT_DIR = os.path.dirname(__file__)
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_DIR,'static'),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATIC_URL = '/static/'
STATIC_ROOT = ''
I was under the impression that Django should be looking for global static content in STATICFILES_DIRS, but it doesn't find the static content for login.html even if I change the url in there to an absolute path to the static folder. Can anyone shed any light on this?
Your problem is that you arent listening to the URL "/static/" nowhere in your urls.py
If you serve your application via a webserver like apache or nginx then this is normal as the webserver would handle the static files itself.
For development Django comes with a built-in static server
to urls.py, at the very end add
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
What this does is to add the /static/ url and let you serve those without a webserver.
This is equivalent to
url(
regex=r'^static/(?P<path>.*)$',
view='django.views.static.serve',
kwargs={'document_root': settings.STATIC_ROOT,}
)
some people will tell you that you need to wrap the URL-rules in a "if settings.DEBUG" to use the dev-only rules, but this isnt needed at all and actually i find that to be a bad advice.
Are you having trouble when using the build in runserver or are you serving using Apache or similar? I've struggled with this a bit. The documentation I follow is: https://docs.djangoproject.com/en/stable/howto/static-files/
The second part is key when you are ready to deploy. You need to define a static root (which will be empty to begin with) and run the manage.py collectstatic command to move the static files from throughout your project into that folder. Then you can serve them from there.
Does changing STATIC_ROOT='' to STATIC_ROOT='/' help?
It seems to me the only difference is that static/pics03.jpg (relative path) exists on the home page, but doesn't on the other.
The absolute path /static/pics03.jpg exists in both cases. If changing STATIC_ROOT doesn't help, just add a / to the beginning of the urls.

Django static files problem

Duplicate of Django staticfiles app help
I'm using Django 1.3 beta and the static files app is confusing. In development mode it is meant to automatically serve files from the STATIC_URL path.
From http://docs.djangoproject.com/en/dev/howto/static-files/
If you're using the built-in
development server (the runserver
management command) and have the DEBUG
setting set to True, your staticfiles
will automatically be served from
STATIC_URL in development.
This didn't seem to work, so I tried a url pattern ('/static/') which routes to the static.serve view. This just 404'd. Somehow it conflicts with the STATIC_URL, if I change it to 'assets/' it will serve the files from static just fine. It's only logical to use '/static' for the static url, but this conflicts.
Url Patterns:
urlpatterns = patterns('',
# Serve static files for *development only*
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
Static files settings:
STATIC_ROOT = '/home/dave/static/flux'
# URL that handles the static files served from STATIC_ROOT.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
Ideally I would like Django to use the static url for seving files in development without having to use any urlpatterns.
If you want to serve up the static files while using the built in Django server you will need to add a urlpattern. This is what I do (add this after all your other patterns:
if settings.DEBUG:
urlpatterns += patterns('',
(r'^static/(.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_PATH}),
)

Categories

Resources