How do I serve CSS to Django in development? - python

I've been all through the documentation, and it just doesn't make sense to me. I ran collectstatic, I set up /static/ directories in both my app and my project directories, I added STATIC_URL and STATIC_ROOT to my settings.py file (but I have no idea how to know if they're set correctly) and {{ STATIC_URL }} still isn't rendering out to anything. It all seems like a heck of a lot of overkill just to connect html to css.
I think I'm lost in the details; could anyone supply a high-level breakdown of this static files idea? I'm afraid I may have mixed instructions for both production and development setups.
MORE: Here's the relevant bit from my settings.py file:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'django.contrib.staticfiles',
'dashboard.base',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
)
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
'C:/Users/Sean/Desktop/Work Items/dashboard/base/static/',
)
And this is the code I'm trying to use in my template:
<link rel="stylesheet" href="{{ STATIC_URL }}css/960.css" />
OK. I made the changes everybody recommended. Here's my new urls.py:
from django.conf.urls.defaults import *
from base.views import show_project
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^dashboard/', include('dashboard.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
('^show_project/$', show_project),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True }),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True }))
urlpatterns += staticfiles_urlpatterns()
Am I missing something? Usually my problems turn out to be something really basic that CS pros take for granted but I miss.

Here's how mine is setup. It sounds like you might be missing the static context processor?
STATIC_ROOT and STATIC_URL
In the settings.py used in development:
STATIC_ROOT = ''
STATIC_URL = '/static/'
And the settings.py used on my production server:
STATIC_URL = '//static.MYDOMAIN.com/'
STATIC_ROOT = '/home/USER/public_html/static.MYDOMAIN.com/'
So, all the static files are located in static/. On the production server, all these files in static/ are collected to /home/USER/public_html/static.MYDOMAIN.com/ where they are served by a different web server (nginx in my case) and not Django. In other words, my django application (running on Apache) never even receives requests for static assets in production.
CONTEXT PROCESSOR
In order for templates to have the STATIC_URL variable available to them, you need to use the django.core.context_processors.static context processor, also defined in settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
# other context processors....
'django.core.context_processors.static',
# other context processors....
)
SERVER STATIC ASSETS IN DEVELOPMENT
Django doesn't get requests for static assets in production, however, in development we just let Django serve our static content. We use staticfiles_urlpatterns in urls.py to tell Django to serve requests for static/*.
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# .... your url patterns are here ...
urlpatterns += staticfiles_urlpatterns()

Have a look at Serving static files in development. You need to define the STATIC_URL and STATICFILES_DIRS to let django.contrib.staticfiles know where to look for files.

The idea behind the static files idea is that you can distribute your development related media file (css/js etc.) on a per-app basis, and allow the static files application to manage and collect all these resources from their various places.
So you tell the static files app where to look for static files (by settings STATICFILES_DIRS), where to copy to them (STATIC_ROOT) and what path to access them (STATIC_URL). When you run collectstatic, it search through the directories and copies all the files it finds into the static root.
The benefit of this is that you can manage your static files on a finer leve:
project/app1/static/css/ # These are css/js for a particular app
project/app2/static/css/
project/app3/static/css/
project/static/css # These might be general css/js for the whole project
static/ # This is where the collectstatic command will copy files to
and after you collectstatic them you will have:
project/app1/static/css/
project/app2/static/css/
project/app3/static/css/
project/static/css
static/app1/css/
static/app2/css/
static/app3/css/
static/css/
When you put your app/site on a production server, you let the webserver (apache, nginx) deal with serving the files by telling it to serve media files at /static/ or /media/ directly, while passing all other requests to the application. When developing though, it's easier to let the development server do this for you.
To do this, you have explicitly tell is server any request for media under /static/ (your STATIC_URL). In your urls.py, put the following (or similar)
from django.conf import settings
...
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True }),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True }))

I have the same problem, and search many answers, but no one give me right answer.
The problem is you don't use RequestContext I think.
You should make a RequestContext as the parameter of Template like
c = RequestContext(request, {
'foo': 'bar',
})
In my views is:
return render_to_response('parts/test2.html', RequestContext(request, locals()))

Related

Django admin static files 404

I'm using Django version 1.10. Project work fine on Debug = True, but when I set it to False is not. Django just can't find static files.
My Django settings looks like:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'master',
'update',
]
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
And the urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^master/', include('master.urls')),
url(r'^update/', include('update.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
uwsgi.ini file
[uwsgi]
chdir = %v
virtualenv = %v/py
module = go_conf.wsgi
master = true
http = :8000
vacuum = true
buffer_size = 64k
max-requests = 100
daemonize = %v/log.txt
I aslo used python manage.py collectstatic, and it collected everything but still not working.
I tried to solve this by reading other articles on this site, but nothing really worked for me.
Hope, that someone will at last help.
This is the Django desing. A quote from the docs for Static file development view:
This view will only work if DEBUG is True.
That’s because this view is grossly inefficient and probably insecure. This is only intended for local development, and should never be used in production.
If you are setting DEBUG=False you are probably going to make it production. If so, your static files must be served by a webserver (eg. Nginx, Apache etc).
check the whitenoice library,
it works great for development and production environment
Radically simplified static file serving for Python web apps

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.

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

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