What am I doing wrong with Django static files? - django

I am working on writing a Django app for the first time, so bear with me if I'm a little behind on things.
Here is an excerpt from my settings.py:
STATIC_ROOT = os.getcwd().replace('\\','/') + '/static'
STATIC_URL = '/static_files/'
STATICFILES_DIRS = (
os.getcwd().replace('\\','/') + '/static'
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Note: I'm hoping that the os.getcwd()... line works. I am pretty sure it's not my problem, but please let me know if this is an issue. It's a placeholder for local dev purposes, so don't worry about it remaining there when I deploy.
My first issue is that template variables don't seem to be working.
An excerpt from my main template file:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL|default:'/static_files/' }}css/base.css" />
I originally just had {{ STATIC_URL }} in there, but that simply returned nothing, so I tried adding |default:'...'. This did successfully generate the given string in the resulting HTML, but still didn't work, which brings me to my second (and more important, honestly) issue.
I can't get static files to work at all. I have tried several different methods here. I have tried putting absolute and relative paths (in various combinations) in each of the above STATIC_* variables, I have tried using the equivalent MEDIA_URL vars instead, and I have tried putting the following into my urls.py:
urlpatterns = ('',
# ...
(r'^static_files/(?P<path>.*)$',
'serve', {
'document_root': '/path/to/django/dir/static_files/',
'show_indexes': True
}
),
)
(I grabbed the above snippet from http://www.arthurkoziel.com/2008/09/02/handling-static-files-django/.)
Now I should note that I will hopefully be eventually serving up static files from a parallel Apache process once initial dev is completed, but I would still really like to know what I'm doing wrong. I haven't been able to find a decently comprehensive tutorial on static files online or on StackOverflow.
All help is greatly appreciated.
EDIT: In case it is important, I am on Windows 7 using Python 2.7.

One possibility - STATIC_URL won't be filled out in your templates unless you're passing in a RequestContext.
Make sure you have something like this in your views:
return render_to_response(template, context, context_instance=RequestContext(request))
As of Django 1.3 you can also use the new shortcut:
return render(request, template, context)
Also, make sure you have 'django.core.context_processors.static' in your context processors.
EDIT: Possible answer to the second problem, try changing
STATICFILES_DIRS = (
os.getcwd().replace('\\','/') + '/static'
)
to
STATICFILES_DIRS = (
os.getcwd().replace('\\','/') + '/static',
)
EDIT 2: More possible fixes
You can delete STATICFILES_FINDERS. You only have it set to the default, so unless you intend to expand it later on, get rid of it (one less thing to go wrong).
You can also get rid of the urlpatterns entry. Not necessary.
Your STATIC_ROOT is probably incorrect. This should be the place where Django will gather all the static files from across your project (including the directories described in STATICFILES_DIRS) when you move to production.
An example from a typical settings.py of mine:
PROJECT_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, 'static'),
)
STATIC_ROOT = '/var/www/myproject_staticfiles/'
That's it!
If you want to test whether Django is finding and placing your static files correctly, try running
python manage.py collectstatic
In my case, that would go through my project directories, find all the static files, then copy them across to '/var/www/myproject_staticfiles/', where I can host them with apache.
The Django dev server automagically serves static files from within your project folder, so no collect_static is required while in dev. You don't even need to set STATIC_ROOT until you go into production.

Related

Django : Page Not Found when trying to access static files

I know there are already several threads on the topic. I've been through most of them (especially all the troubleshooting listed in this one) but I can't figure out my issue.
I am trying to use a Bootstrap template in my Django project, and I'd like to simply start by accessing the files in the /static/ directory. My project directory looks like this :
Whenever I try to load the page http://localhost:8000/static/theme/assets/css/style.css it returns a Page not found error (and obviously no CSS/JS content appears on my index).
Here are my settings:
I have debug = True
ÌNSTALLED_APPS contains django.contrib.staticfiles
settings.py looks like this :
STATIC_URL = "/static/"
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),)
But I still can't access anything from the /static/ directory.
I tried to access the CSS and JS files in base.html this way :
{% load static %}
...
<link href="{% static 'theme/assets/css/style.css' %}" rel="stylesheet">
I really have no clue how I could solve this.
Thanks in advance for your help !
Is base.html properly bound to a URL and to a view function via a URL dispatcher ? Can you access that file from your browser ?
If yes, try to substitute this line
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),)
with this one
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)

Problem while loading static files|| django

iam learning Django i have learned pretty much. I used static method to rendered css and other static files. But changes iam making to css which is in static files are not reflacting on webpage . i have to close all files and restart vscode again to see those changes. I have not added code because im not getting any error at all .
( example :: i have changed font size of all anchors . Normally it should be changes on webpage after saving and refreshing the page. but in this case font size is not changing. i have to close all files and reopen them and after starting the server again i can see those changes which i made to anchor tag. )
Any one who knows why because to see changes restart whole project will never be a good option. thanks in Advance
At the beginning of your code use {% load static %} and where ever you want to use the files from static folder use {% static 'name of your file' %}
Make sure you've not added your static folder in your base directory. In such case update your settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
you can use whichever name you like instead of assets

Django Templates: How does it decide where to load a template?

I was following the Django Girls Tutorial up to the point where we add the login capabilities and I've gotten to a point where it tries to load from a different template folder than I want.
I have all my blog templates in blog\templates\blog\, etc. and that is where Django is looking for my login.html. However, in the tutorial (and as a result in my folder structures), the path for login.html is: mysite/templates/registration/login.html. So how would I make Django look there?
Sorry if this is a stupid question.
Django will look to your settings.py for how to load templates, and the order in which it should try to load templates. It's likely that you haven't configured django to look for templates in mysite/templates.
There's a setting called TEMPLATE_DIRS which is a list of absolute paths for your template folders. So in your settings.py file, try something like below. Read my comments to see what each line does.
# create a variable that stores the absolute path to your project's root directory
# you might have something like this already defined at the top of your settings.py
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
# this is the default value for TEMPLATE_LOADERS
# which says to look at the `TEMPLATE_DIRS` variable, and then in each of your app's subdirectories for templates
TEMPLATE_LOADERS = ('django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader')
# the special sauce. tell django to look at the "templates" folder
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'), )

Getting Page not found (404) in Django 1.3.1 from bad url pattern

I am following along with this Django blog tutorial and can not get the url pattern given in the tutorial to work properly. The url.py code the author gives is
(r'^static/(?P
.*)$', 'django.views.static.serve',
{'document_root': 'c:/static/adornment'}),)
and I adapted it to my Linux set up like this
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
(r'^static/(.*)$', 'django.views.static.serve',
{'document_root': '/home/sez/blog/static/image.png'}
),
)
and after going to http://127.0.0.1:8000/static/image.png I received the following error
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/static/image.png
'image.png' could not be found
How can I make this work?
Change up your 'document_root' to be a directory, and make sure your STATIC_URL setting is set to /static/
The likely reason for the behavior you were experiencing is as follows. You probably have 'django.contrib.staticfiles' included in your INSTALLED_APS in the "settings.py" file. In that case, when you run "manage.py runserver" (and you have DEBUG = True in your "settings.py"), static files will be automatically served from your STATIC_URL by the staticfiles app and not by your 'django.views.static.serve' URL pattern. However, in your case staticfiles app is not set up correctly and won't find your 'image.png' file. You might want to read more about conventional serving of static files here: Managing static files.
For that matter, STATIC_URL is not supposed to be a filesystem path like you have now: STATIC_URL.
When you made it that way, you effectively disabled staticfiles app and your code started working as a result :)
So, to solve your problem "correctly", you need to either make sure that STATIC_URL and the URL path in your "urls.py" are different, for example, make one of them "/static/" and another one "/media/" (or something else), or just remove "django.contrib.staticfiles" from your INSTALLED_APPS altogether if you don't use it. (And, of course, the advice about making 'document_root' a directory was entirely correct. You can read more about using 'django.views.static.serve' here: Serving static files in development.)

Django : How do I call "reverse" on a link to a static image file?

In Django, I have images stored in site_media like this :
/site_media/somepath/image.jpg
The urls.py file has been set up to server these using :
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$', 'staticfiles.views.serve')
)
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$', 'staticfiles.views.serve')
)
So how can I make a reverse() or {% url %} call to one of these images?
It's probably easier to just use:
{{ MEDIA_URL }}somepath/image.jpg
assuming you've set up the MEDIA_URL setting in your settings.py.
Also, you really don't want to serve static files through Django in a production environment. From the docs:
Using this method is inefficient and insecure. Do not use this
in a production setting. Use this only for development.
One more thing - what is staticfiles.views.serve? Django has a built in system for serving static files, though the disclaimer above still applies.
You probably want to serve static files straight from Apache/nginx/whatever. It'll be heaps quicker.