Django static files problem - python

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}),
)

Related

Django Static Url Error, Not Loading

I'm currently mad at Django (1.9) right now! The saddest thing is 'Static URL' is the one giving me problem. 'Media URL' is working fine, no problem, but the static url is giving a huge headache.
in my settings_dev.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(PROJECT_PATH,'../static/')
STATIC_URL = '/static/'
when I add the below tag:
{% load static from staticfiles %}
<script type="text/javascript" src="{% static 'datepicker/js/bootstrap-datepicker.js' %}"></script>
The js file won't load. when I check my source code, it will display the below link.
<script type="text/javascript" src="/static/datepicker/js/bootstrap-datepicker.js"></script>
And when I click it will redirect me to
http://127.0.0.1:8000/static/datepicker/js/bootstrap-datepicker.js
And display
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/static/datepicker/js/bootstrap- datepicker.js
Now, I adjusted my urls.py to
if settings_dev.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings_dev.MEDIA_ROOT, 'show_indexes': True}),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings_dev.STATIC_ROOT, 'show_indexes': True}),
)
Yet, I'm still getting the same error!! Page not found issues.
Project Directory
PROJECT NAME: Book/
SUB DIRECTORY:
media
static
Template
book
bookapp
manage.py (this is a file)
What am I missing?
Okay to make things clear for you.
STATIC_ROOT is that directory where all your static data gets collected when you want to serve your files on another server, say APACHE or NGINX or maybe on Heroku or so.
If don't want just want to run your web-app on your local development server, you don't require python manage.py collectstatic and hence you don't need STATIC_ROOT.
All you need is STATIC_URL and in case you have your static files at some other location as well then you also need STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),].
So you'll be having a folder named `static' at the base directory level where django will look for your static files.
If you specify the same folder for STATIC_DIRS and STATIC_ROOT then you'll automatically get an error. Django won't allow you to do that as technically you are trying to give the same directory for two different purposes.
See this for a detailed explanation -> Differences between STATICFILES_DIR, STATIC_ROOT and MEDIA_ROOT
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),]
That line is enough for serving your project static folder files... And you have to set this in your urls.py
urlpatterns = [
...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

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.

How do I display an image on my webpage in Django?

I want to display an image on my website. I've been looking through the Django documentation and the other posts on stackoverflow, but I haven't gotten this to work.
I have an image name 'under-construction.jpg'. It lives in the /home/di/mysite/myapp/static/images directory.
I have a template like this:
<img src="{{ STATIC_URL }}images/under_construction.jpg" alt="Hi!" />
in my views.py I have this:
def under_construction(request):
return render(request, 'under_construction.html')
In my settings.py, I have this:
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
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.
'/home/di/mysite/myapp/static',
'/home/di/mysite/myapp/static/images',
)
I executed ./manage.py collectstatic and it put a lot of files in /home/di/mysite/admin and /home/di/mysite/images. What do I have to do get my image to show up?
All you need to do is edit settings.py to be as the 4 following points and create a new folder (static) in the same folder settings.py is located
in the folder static you can create another folder (images) in it you can put the (under_constructioon.jpg)
STATICFILES_DIRS = (os.path.join( os.path.dirname( __file__ ), 'static' ),)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',)
STATIC_URL = '/static/'
STATIC_ROOT = ''
after you're done with the prev. points you can write
<img src="{{ STATIC_URL }}images/under_construction.jpg" alt="Hi!" />
I have faced same problem displaying the static image. suffered a lot and spent a lot lot of time in this regard. So thought to share my settings.
settings.py
STATIC_ROOT = ''
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
import os.path
STATICFILES_DIRS = (
"D:/temp/workspace/offeronline/media",
(os.path.join( os.path.dirname( __file__ ), 'static' )),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
urls.py
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ... and at the end of the file add the following line
urlpatterns += staticfiles_urlpatterns()
and finally added the following code to the template tag and it worked
<img src="{{ STATIC_URL }}images/i1.png" />
I have solved that problem like this.
STATIC_ROOT = '/path/to/project/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
)
Django will not directly get files directly even you do this. You need to link this static directory for each application of yours. Just go to the django app dir run following command..
cd /path/to/project/my_proj/my_app
ln -s /path/to/project/static/
This will work only in debug mod. You need to set DEBUG = true in settings.py file. This should work with django's development server.
Django won't serve any static file in production mod. You need to serve static files with web-server in production mod.
More information can be found here..
Django does support static files during development, You can use the django.views.static.serve() method in view to serve media files.
But using this method is inefficient and insecure for production setting.
for Production setting in Apache
https://docs.djangoproject.com/en/1.2/howto/deployment/modpython/#serving-media-files
set STATIC_ROOT = /path/to/copy/files/to
have you added
urlpatterns += patterns('django.contrib.staticfiles.views', url(r'^static/(?P<path>.*)$', 'serve'),
or you can also do this
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()
and of course try not to server static files through django it does have some overhead instead configure your http server to serve them, assuming you have an http server (nginx is quite good).

django, runserver_plus - admin media files served from wrong path

The configuration below works fine on my remote host (same dir structure, same django), all admin media are served properly
settings
MEDIA_ROOT = '%s/static/' % FS_ROOT
STATIC_DOC_ROOT = '%s/static/' % FS_ROOT
MEDIA_URL = '/static/'
ADMIN_MEDIA_PREFIX = '%smedia/' % MEDIA_URL
urls
(r'^admin/', include(admin.site.urls)),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '%s/static' % FS_ROOT }),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '%s/media' % FS_ROOT }),
django 1.2.0 # ubuntu 9.10, http://127.0.0.1:8084/ via runserver_plus
Admin media files are stored under /static/media/ in my project root dir and every static files/dirs under /static/. All statics are served fine, only the admin media are taken from the default django's admin media files. What am I forgetting and why it does affect the project only on my localhost? I've tried to everride /static/media/ path in the urls in various ways, but still nothing.
There are two solutions:
You can either set a hostname in ADMIN_MEDIA_PREFIX as suggested in this answer.
Or you can start the development server with the --adminmedia parameter as described in the django documentation.

Serving static media during Django development: Why not MEDIA_ROOT?

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.

Categories

Resources