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

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!

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/'.

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.

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.

Related

(Django) How to apply css?

I want to apply CSS on my Django project.
CSS path in my index.html is right but it doesn't work well.
My index.html page show up well in my site,
--app_index
----index.html
----bootstrap
-------css
-----------abc.css
-----------abc2.css
So, must I modify the URL.py file too?
You need to configure static files in your Django app. The following links should help guide you in the right direction:
http://www.tangowithdjango.com/book/chapters/templates_static.html
https://docs.djangoproject.com/en/1.7/howto/static-files/
You will set up your index.html for example in a template directory that can access your static files (e.g. CSS, javascript, static images, etc.) that are located in your static directory.
In response to your question concerning modification of urls.py, the answer is yes. As you will see in the links on configuring static files within your project, you have to add some code to your urls.py. An example of this code might look like this:
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}),
url(r'^__debug__/', include(debug_toolbar.urls))
)
During development Django serves your static files hence the above code, but during production your static files are served via your configured server (e.g. Apache, nginx).

Django 1.3 Static Files

Like the 1 billionth static file question about Django 1.3. I've been searching and trying so many things but nothing seems to work for me. Any help would be appreciated. Will try and give as much information as possible.
URL FILE
urlpatterns = patterns('',
url(r'^projectm/statictest/$','project_management.views.statictest'),)
VIEW
def statictest(request):
return render_to_response('statictest.html',locals())
TEMPLATE
<html><head><title>Static Load Test Page</title></head>
<body>
{% load static %}
<img src="{{ STATIC_URL }}testimage.jpg" />
</body></html>
SETTINGS
STATIC_ROOT = '/home/baz/framework/mysite/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = ('',)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_DIRS = (
"/home/baz/framework/mysite/templates"
FILES
-bash-3.2$ pwd
/home/baz/framework/mysite/templates
statictest.html
-bash-3.2$ pwd
/home/baz/framework/mysite/project_management/static
-bash-3.2$ ls
testimage.jpg
Not too sure if there is any other information that would be helpful. But basically when I go to this test page and check the page source, the url is pointing to
<img src="/static/testimage.jpg" />
However the image does not load. I have tried this on multiple browsers too. Maybe I am missing an imort statement somewhere?
cheers for the help
Are you using the built in runserver command or do you serve the Django app some other way?
If you use runserver then your problem is that you don't tell Django where to find your static assets in the filesystem. You need to set STATIC_ROOT to a filesystem path where your static assets can be found. Try setting it to: /home/baz/framework/mysite/project_management/static/
If you are using a different server (like gunicorn behind Nginx for example) then it is the responsibility of the front-end server to intercept requests for /static/ and serve them for you.
Also remember to run the ‘collectstatic’ management command once you have set ‘STATIC_ROOT’.
https://docs.djangoproject.com/en/1.4/howto/static-files/#deploying-static-files-in-a-nutshell

Django cannot find my media files (on development server)

The media is currently on my local development machine.
My MEDIA_ROOT, MEDIA_URL, ADMIN_MEDIA_PREFIX and are specified as below:
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), "media")
MEDIA_URL = '/media/'
SITE_URL = 'http://localhost:80'
ADMIN_MEDIA_PREFIX = '/media/admin/'
There is no 'admin' folder but that shouldn't make a difference I don't think.
In the urls.py file I have:
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
I am at a loss as to what I should do to get it working.
[I am trying to learn django and am working with an existing project that's pretty hairy]
You're mixing and matching pre and post-Django 1.3 static file handling. Originally all static files were served from MEDIA_URL, but Django 1.3 introduced the staticfiles contrib package and the associated STATIC_ROOT and STATIC_URL settings. django.views.static.serve utilizes the new staticfiles app, which you haven't set up.
Assuming you're running Django 1.3, first, you'll need to add 'staticfiles' to your INSTALLED_APPS. Then, you'll need to define STATIC_ROOT and STATIC_URL. The standard location is a project-root level directory named "static".
You'll also need to add the staticfiles template context processor:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.static',
)
This will make the STATIC_URL variable available in your templates, so you can reference your resources with something like {{ STATIC_URL }}css/style.css
All your static resources will also need to go into an app(s)-level directory named "static". The actual project-root level "static" directory is never directly used. It's simply the place where the collectstatic management command dumps all your static resources for use in production.
If you want project-wide static resources (not tied to any one particular app), you'll need an entirely separate directory (i.e. not the same as MEDIA_ROOT or STATIC_ROOT). I tend to use one named "assets". You'll then need to tell Django to look in here for static resources as well with the STATICFILES_DIRS setting:
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__), 'assets'), # or whatever you named it
)
MEDIA_ROOT/MEDIA_URL are now only used for user uploads (e.g. any file created through FileFields and ImageFields, so you still need it, but you won't ever manually store anything there.
When you reach production, your webserver will need to serve both MEDIA_ROOT and STATIC_ROOT at MEDIA_URL and STATIC_URL, respectively. You'll also need to run:
$ python manage.py collectstatic
To make Django compile all your static files into the directory specified by STATIC_ROOT.
works with django 1.8 - 1.11:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
https://docs.djangoproject.com/en/1.11/howto/static-files/#serving-files-uploaded-by-a-user-during-development
note that Django documentation states that this is
not suitable for production use
(obviously unless you use if settings.DEBUG: part)
On development server, this page may help you.
https://docs.djangoproject.com/en/1.2/howto/static-files/
By adding follow code to urls.py:
if settings.DEBUG:
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/path/to/media'}),
)
With python-django 1.7 I used
if settings.DEBUG:
urlpatterns = patterns('',
(r'^$', 'blenderx3d.first_step.views.index'),
(r'^media/(?P<path>.*)$','django.contrib.staticfiles.views.serve'),)

Django staticfiles app help

I've having a little issue with Django's staticfiles app.
I have added
'django.contrib.staticfiles',
to my INSTALLED_APPS and have added
STATIC_URL = '/static/'
STATIC_ROOT = '/Users/kevdotbadger/django/mylook/static/'
to my settings.py file.
All my static files are located within the STATIC_ROOT folder on my Mac.
Now, within my template I use
{{ STATIC_URL }}
which correctly renders to /static/.
However
{{ STATIC_URL }}css/style.css
result in a 404 error. I'm using the 'runserver' command as the server.
Is there something I'm missing?
I implore you to read the howto docs here: http://docs.djangoproject.com/en/dev/howto/static-files/
In short: STATIC_ROOT is only used if you call the collectstatic manangement command. It's not needed to add the directory to the STATICFILES_DIRS setting to serve your static files!
During development (when the automatic serving view is used) staticfiles will automatically look for static files in various locations (because you call its "serve" view with a path to a static file). For this search it'll use the so called "finders" (as defined in the STATICFILES_FINDERS setting).
One of the default finders is the AppDirectoriesFinder, which will look in the "/static/" directory of each of the apps of yours INSTALLED_APPS setting.
Another default finder is the FileSystemFinder, which will look in directories you specify in the STATICFILES_DIRS setting.
BTW, both these search patterns are similar to how template loading works.
The same technique will be used when running the collectstatic command, except that it now will collect the files from the various locations (using the same finders as above), putting the found files into STATIC_ROOT, ready for deployment.
If you want just a solution - scroll down to the "Solution".
Overview
I was discovering the same problem yesterday. Here is what I found:
All you need is appropriate static finder, that will find your STATIC_ROOT and all its contents, but there is no such finder. Here are default finders:
django.contrib.staticfiles.finders.AppDirectoriesFinder - search installed django applications dirs for 'static' folder, but most of them use obsolete 'media' folders for now.
django.contrib.staticfiles.finders.FileSystemFinder - use all dirs mentioned in the STATICFILES_DIRS, but you can't add STATIC_ROOT into it.
django.contrib.staticfiles.finders.DefaultStorageFinder - search static in your DEFAULT_FILE_STORAGE which is django.core.files.storage.FileSystemStorage by default and it points to your MEDIA_ROOT
Solution
That's all, no additional choices. There are no choices to use STATIC_ROOT for now (in Django 1.3).
So I've just wrote my own custom finder for these needs:
My custom static finder file: finders.py:
from django.core.files.storage import FileSystemStorage
from django.contrib.staticfiles.finders import BaseStorageFinder
from django.conf import settings
class StaticFinder(BaseStorageFinder):
storage = FileSystemStorage(settings.STATIC_ROOT, settings.STATIC_URL)
settings.py:
STATICFILES_FINDERS = (
'finders.StaticFinder',
)
If you want to use it with another finders - I suggest to put them after it inside STATICFILES_FINDERS
And remember: this solution should be used only in development needs and never on production!
I found a quick and easy workaround to serve project global static files during development:
Start a new app that contains your projects static files (e.g. "manage.py startapp static_content")
Create a folder named 'static' in that app and put your static files there.
Add your new app to the list of installed apps
First of all, make sure that you have static serve enabled in your urls.py FOR DEVELOPMENT ONLY.
Also, you may have an extra slash in there. If your STATIC_URL == '/static/', then
{{ STATIC_URL }}/css/style.css should be {{ STATIC_URL }}css/style.css.
STATIC_ROOT = '/home/ws/be/bla/'
STATICFILES_DIRS = ('/home/ws/be/static/',)
STATIC_URL = '/static/'
This works for me. STATIC_ROOT must differ from STATICFILES_DIRS (Django version 1.4 pre-alpha SVN-16436)

Where to put a Django template's dependent files?

My Django templates use a lot of related stuff: images, style sheets, etc.
Where should I put these file, or how should I refer to them in the template itself?
For now I'm using the development server.
I know it's a really common thing, but I can't really figure it out.
I put them inside a folder named static, which is in the web project's top level folder.
Example:
/static/img/
/static/js/
/static/css/
/templates/
urls.py
settings.py
I then have the following rule in my urls.py file:
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
My settings.py contains:
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'static').replace('\\', '/')
ADMIN_MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'static/admin').replace('\\', '/')
Maybe you can read the doc http://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files
We put ours under /media. Everything that is specifically tied to the layout of the sites is further separated. Of course none of this static content is served by Django on the production site. They often aren't even on the same physical server.
/media
/images - this is for content-specific images
/video - these next 2 are normally symlinks to a /big_content folder ...
/audio - so that they aren't included in our mercurial repository.
/layout - everything that is tied to the basic templates.
/css
/js
/images

Categories