I have had this problem for a while now, I have been trying to move my CSS file all over the place and changing the settings, and even messing with the media url stuff, which I don't believe I should be now that I have read other questions.
My CSS file is in the /home/justin/test/static/ directory. My templates are in the /test/templates directory.
My settings are:
STATIC_ROOT = '/home/justin/test/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
'/home/justin/test/static/',
)
My urls are:
urlpatterns = patterns('',
url(r'^$', 'views.home'),
# Static Files
url(r'^static/(?P<path>.*)$','django.views.static.serve', {'document_root':settings.MEDIA_ROOT}),
)
I have all three in my main template.
<link rel="stylesheet" href="/static/style.css" />
<link rel="stylesheet" href="{{ STATIC_URL }}style.css" />
<link rel="stylesheet" href="{{ STATIC_URL }}/style.css" />
They come out:
<link href="/static/style.css" rel="stylesheet"></link>
<link href="style.css" rel="stylesheet"></link>
<link href="/style.css" rel="stylesheet"></link>
The first comes out to the correct file, but it doesn't work.
Any help is really appreciated. Thank you.
My views.py:
from django.shortcuts import render_to_response
def home(request):
return render_to_response('index.html',{})
My error from the terminal is:
[16/Aug/2013 21:00:21] "GET /static/style.css HTTP/1.1" 500 1729
You need to pass request in RequestContext of your views
def home(request):
return render_to_response('index.html', locals(), context_instance = RequestContext(request))
Only then your session data will be passed to the template and {{ STATIC_URL }} will work.
Here are some tips to help you solve this problem.
First, anything to do with MEDIA_ is referring to files that are uploaded to the system by users; and STATIC_ refers to files that are part of your application.
STATIC_ROOT should point to the file system path where the collectstatic command will dump all the static files from all your applications. When you are deploying the application into a production environment, you run collectstatic (which will overwrite everything in the directory pointed to by STATIC_ROOT) and then copy the contents of this directory to a location that is mapped to the url that STATIC_URL points to.
In summary:
If your application needs any static files (images, javascript, css, etc.) create a directory called static in your application's directory (the same location where you have models.py) and add the files there.
STATIC_ROOT should point to a directory where all the images, css, javascript, etc. will be dumped by the collectstatic command. This is only used when you want to move your application to a production server. The collectstatic command will grab all the files in all the static directories in your applications that are listed in INSTALLED_APPS (including the ones from the django.contrib like the admin interface) and dump them in this directory. You would then take this directory and copy or move it to your web server.
STATICFILES_DIRS is a directory where any static files that are not part of any specific application should be stored. If this location is set, then django will also look here for static files.
STATIC_URL = the URL path that is configured in your web server to point to the location where all the files in STATIC_ROOT are located.
The {% static %} tag will always point to the STATIC_URL variable. In order to use this tag you must have {% load staticfiles %} at the top of any template that is using the tag; even if the template is inheriting from one that already as the load line in it.
You don't need anything fancy in your urls.py unless you are using django to serve your static files (which you should not do). Use the web server to handle static files. If you are running with DEBUG = True and using runserver, then django will take care of handling static files for you automatically as a courtesy during development.
For any user uploaded files which are controlled by the various MEDIA_* settings you need to handle these manually during development; and for this you can use the following snippet in your urs.py. Again, keep in mind this is only for development - do not use this in production:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Please read the static files section in the manual; from where I have summarized the above points.
Finally, you should use the render shortcut when using methods in your views. This makes sure that the proper request context is always sent.
you must use this tag ({% load static from staticfiles %}) in your template :
{% load static from staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" />
In your urls, you should serve from the STATIC_ROOT not the MEDIA_ROOT setting
url(r'^static/(?P<path>.*)$','django.views.static.serve', {'document_root':settings.STATIC_ROOT})
Also, you need to pass RequestContext on your views, like stated in other answers.
In development mode (which means DEBUG=True in settings.py), to serve static files
Simply put the following lines in urls.py
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()
In production mode, you should use nginx/apache in front of django to serve static files.
Refs: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/
There's a line in your question:
url(r'^static/(?P<path>.*)$','django.views.static.serve', {'document_root':settings.MEDIA_ROOT}),
Normally, settings.MEDIA_ROOT is for user uploaded files, which is a different folder from settings.STATIC_ROOT.
Related
I have a strange issue that's occurred on several django projects and I'm trying to figure out a fix for it. For some reason, all the static files for the admin area load properly including the js, css, and images but 2 files for the side nav bar (which are in my static directory along with everything else) wont load. The files are the nav_sidebar.css and nav_sidebar.js.
I've figured out a work around and added these inline in the admins base.html template and deleted the links to these files. This works but it's kind of ridiculous that it manages to load all other static assets fine but not these particular files. I have my static root and directories set up properly, have nginx pointing to the correct static directory, and have done collect static and restarted the server. Everything I could possibly think of but it doesn't work.
Considering this has happened on 3 straight projects, I think this is some kind of bug rather than an error on my end.
So I was able to answer my own question in the end and for anyone else that comes across this problem here are the steps I took.
For the admin static files, before you run collect static are being sourced directly from the wherever your python(versionNumber)/site-packages/django/contrib/admin/static is located. Unless you run collect static, or manually copy and paste them into your static files directory, these admin files wont be there.
Now I'm sure this is basic knowledge for any django user and I even did this and the error still persisted. What I found, is that I set my static urls up like:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
And for some reason, django was still sourcing the admin files from that same directory the django source is located. So I simply changed the url path and static root to:
STATIC_URL = '/staticfiles/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
And ran manage.py collectstatic again and that fixed my admin area and everything is working properly now.
These two files are introduced in django 3.1 for nav_sidebar feature. In admin/base.html, it says:
{% if not is_popup and is_nav_sidebar_enabled %}
<link rel="stylesheet" type="text/css" href="{% static "admin/css/nav_sidebar.css" %}">
<script src="{% static 'admin/js/nav_sidebar.js' %}" defer></script>
{% endif %}
is_nav_sidebar_enabled by default is enabled. Did you put something in the root urls.py to disable that?
something like:
admin.site.enable_nav_sidebar = False in your root urls.py?
The doc about the new nav_sidebar feature is here
I could load css file on Django html like this
{% load staticfiles %}
<link rel="stylesheet" href="{% static "css/style.css" %}">
I wonder why I can't load css file that is under templates folder.
<link rel="stylesheet" href="css/style.css">
Is there a way to load file that is under templates folder on Django HTML?
Why does Django wants me to put {% static "css/style.css" %} this format on all static files? Is it because much faster to load?
What If I load file that is under templates folder? Is it slow to load?
Templates and static assets are two differents types of assets that need to be managed differently for security purposes.
All js, css and images files need to be provided to clients in order for your website to be working. They are handled from the client side so they need to be available. So static asset folder is made to be available, if you check view source and follow the link of these assets you'll see they can be opened directly in your broswer.
Templates however are used by django itself to generate the output that is set via your views. When a user opens a page, he doesn't access the template itself but the rendering made by django. So the template folder isn't accessible to end user by design, including the files that are in it. So the only things a user can access from a django application are the responses given by the views, that are based on urls patterns and the templates, and assets that are in static folder. So you can't, and shouldn't, link to static assets from anywhere else but your static folder.
As I can see it, you have missed the concept of the templates and the static files in Django.
First of all, there are two independent mechanisms: loading a template file (your future HTML file) and loading your static files (css, js, images).
When loading a template Django uses TEMPLATE_LOADERS (docs), which are basically defined in your settings.py as:
TEMPLATE_LOADERS = (
# Loads templates from DIRS setting:
'django.template.loaders.filesystem.Loader',
# Loads templates from your installed apps:
'django.template.loaders.app_directories.Loader',
)
You can define a location of yout templates by setting DIRS (if you are using Django >= 1.8) or TEMPLATE_DIR (if Django < 1.8). There are several more steps in rendering your template such as: template context processors and so on, but it is all listed in the documentation.
Now about static files.
Static files are served by django.contrib.staticfiles app (docs) when DEBUG = True. In production it is done by Nginx, Apache or other Http-Servers.
When loading a static file Django uses STATICFILES_FINDERS. They are usially defined as:
STATICFILES_FINDERS = (
# Loads static files from STATICFILES_DIRS:
"django.contrib.staticfiles.finders.FileSystemFinder",
# Load static files from installed apps:
"django.contrib.staticfiles.finders.AppDirectoriesFinder"
)
There are two main settings to care about: STATIC_URL and STATICFILES_DIRS.
STATIC_URL is basically just a prefix, which is used to get your static files. It is almost always just '/static/'. And in STATICFILES_DIRS there are paths to your static files folders. It is sometimes extended to include node_modules, bower_components or things like that.
When dealing with static files in templates you need to append your STATIC_URL to your file's URL. The easiest way to do that is {% static %} tag.
A lot of confusion comes with STATIC_ROOT. It is just a path, where all your static files will be collected in production after running collectstatic management command.
Django 1.6
I'm having trouble serving my static files for my Django Admin.
urls.py:
urlpatterns = patterns('',
url(r'^$', 'collection.views.index', name='home'),
url(r'^collection/', include('collection.urls')),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
settings.py
...
MEDIA_ROOT = '/Users/me/projectdir/media/'
MEDIA_URL = 'media/'
STATIC_ROOT = '/Users/me/projectdir/static/'
STATIC_URL = 'static/'
...
template (base.html)
<!DOCTYPE html>
<html lang='en-us'>
<head>
<title>Mysite</title>
{% load static %}
{% block links %}
<link href="{% static 'css/bootswatch-simplex.css' %}" rel="stylesheet" type="text/css">
<link href="{% static 'css/custom.css' %}" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="{% static "favicon.ico" %}">
{% endblock %}
<script src="{% static "lib/bootstrap-3.1.1-dist/js/bootstrap.js" %}"></script>
<script type="text/javascript">window.__admin_media_prefix__ = "{% filter escapejs %}{% static "admin/" %}{% endfilter %}";</script>
</head>
...
Django is serving my admin OK, just without static files: CSS, JS, etc.
Static files for my public-facing pages work fine.
If I change STATIC_URL to '/static/', then the opposite is true: the admin is fine, but my public pages lose their static files.
Here's the weirdest part. If I "view source" of my admin pages in my browser, it shows the correct URL for static pages, for example:
/static/admin/css/base.css
But if I actually follow the link, it changes it to this:
http://localhost:8000/admin/static/admin/css/base.css
I think it's checking for static files relative to localhost:8000/admin/static/ instead of just localhost:8000/static/. It adds an extra "admin" level to the url, like static is part of the domain. I just can't figure out how to get rid of it.
I have tried collectstatic, but it doesn't help. The static files are in my static directory, they're just not being served. I can type in, say, http://localhost:8000/static/admin/css/base.css and I get the right CSS file (in plaintext). The files are there. I bet something is wrong with my configuration.
I've emptied my caches, restarted my dev server, etc. No beans.
ideas?
Use django-admin.py collectstatic or go to ~/django/contrib/admin/static and copy the admin folder(which contains the static files) and paste them into your project's static directory.
**EDIT**
A desperate or clumsy solution you can try for: change your STATIC_URL to '/static/', as from question I saw this:
If I change STATIC_URL to '/static/', then the opposite is true: the
admin is fine, but my public pages lose their static files.
Then check with inspect element/firebug, see what urls are being served in public pages. Probably a '/' missing or added a '/'. Adjust it, and see if it works.
OK, I figured it out. There was some confusion in my settings files, and I did not have STATICFILES_DIRS correctly set.
In the end, I implemented the version-controlled settings files discussed in Two Scoops of Django 1.6, with this in my settings:
from unipath import Path
BASE_DIR = Path(__file__).ancestor(3)
MEDIA_ROOT = BASE_DIR.child('media')
STATIC_ROOT = BASE_DIR.child('static')
TEMPLATE_DIRS = (
BASE_DIR.child('templates'),
)
STATICFILES_DIRS = (
BASE_DIR.child('myapp').child('static'),
)
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
With this, my static files are being served correctly, both in admin and without. My media files, on the other hand, did not work without changing my urls.py in development, according to the accepted answer here. I did not have to do the same for my static files.
Anyways, I hope this helps anyone else banging their head against this particular wall.
I faced the same issue for two times.
The way i solved it was by pasting the static files of admin into static folder mentioned in the code -
cp -r /usr/local/lib/python2.7/site-packages/django/contrib/admin/static/admin /home/ec2-user/mywork-Deployment/mywork/static
This one definitely works and saves a lot of time and troubles.
Hope it helps!
First You need to try:python manage.py collectstatic
then u got any errors just follow these steps
step1
**Remove these code from you**r settings.py
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
'/home/uour project/src/project name/static/',
) //remove these lines
step2
Replace with it replace with these codes
STATIC_ROOT = os.path.join(BASE_DIR, 'static') //add these line
step3
open terminal and type:python manage.py collectstatic
If it helps anyone, I will share what the issue was with my code. Probably my stupid mistake but may save someone's time:
So, basically. my settings.py variables were something like this:
AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/"
STATIC_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/static/"
I inspected the admin page css src tags and found out the URLs were like this:
(Notice two forward slashes in the URL)
https://bucket-name.s3.amazonaws.com//admin/css/login.css.
So I changed my variables slightly and everything loaded fine.
AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com"
STATIC_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/static/"
That corrected the faulty URLs and static files loaded perfectly.
The way that worked out for me was I referenced the static admin files in my settings.py file. I hope this helps someone :)
'./static/admin/',
in my case i only set debug to True and they loaded , strange but worked somehow
I'm trying to follow these instructions to enable static files in my Django project.
I have
STATIC_URL = '/static/'
in my settings.py file. I have 'django.contrib.staticfiles', added to the INSTALLED_APPS = (...) part
I created a folder mysite/static/mysite and put my files there. But after I run the server, I cannot access my files at http://127.0.0.1:8000/static/mysite/style.css.
What I have done wrong?
In settings.py include this:
import os
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static/mysite/'),
)
And in your urls.py include these lines at the end:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
Hope it helps.
I can suggest a couple things to check:
In my projects at least, the static folder is in the app directory, not the project directory. For example, mysite/myapp/static/myapp/img.jpg rather than mysite/static/mysite/img.jpg. Your project might not be looking in the right place.
Make sure that {% load staticfiles %} is in your html template before linking the files.
When you link a file in your html template, rather than direct urls like
<link rel="stylesheet" href="myapp/css/custom.css">
use
<link rel="stylesheet" href="{% static 'myapp/css/custom.css' %}">
This was enough to get static files working in my projects, without having to modify urls.py or manually set PROJECT_ROOT or STATICFILES_DIRS.
I put the image("hi.png") and css file in /home/user1/djangoblog/blog/static
In templates i have <img src="{{ STATIC_URL }}images/hi.png" />
I edited the settings.py =>
STATIC_ROOT = ''
STATIC_URL = "/static/"
STATICFILES_DIRS = (
"/home/user1/djangoblog/blog/static/",)
The web page source returns =>
<div><img src="/static/images/a.jpg" /></div>
If the views.py => The image is not displayed on the web page.
now = datetime.datetime.now()
#return render_to_response('current_datetime.html', {"foo": now}, context_instance=RequestContext(request))
t = loader.get_template('current_datetime.html')
c = Context({'foo': now})
return HttpResponse(t.render(c))
But if the views.py => it displays the images on the web page.
return render_to_response('current_datetime.html', {"foo": now}, context_instance=RequestContext(request))
It looks like it's a problem with HttpResponse or RequestContext. How can i fix this problem with HttpResponse or RequestContext?
You need to read the staticfiles docs more carefully.
You specify the absolute path to your static directory with STATIC_ROOT and the URL that directory can be accessed at through a browser via STATIC_URL. Your main static directory should never go in STATICFILES_DIRS. That setting is only to allow you to specify additional directories that should be processed while running the collectstatic management command.
In general, you never use your actual static directory. In development Django serves files from each app's static directory and any directories in STATICFILES_DIRS (excluding the main static directory). In production, you run the collectstatic management command and then setup your main webserver (Apache, Nginx, etc) to serve files from STATIC_ROOT. Django never serves anything from the main static directory (STATIC_ROOT).
I suspect the problem is that you don't have the staticfiles context processor in your settings file. That's the reason that /static/ isn't being inserted where you've put {{ STATIC_URL }}.
It's as simple as putting
'django.core.context_processors.static',
Into the list of context processors (TEMPLATE_CONTEXT_PROCESSORS) in your settings.py file.
Update
I added this in TEMPLATE_CONTEXT_PROCESSORS but still that didn't work. – guru 3 hours ago
Adding 'django.core.context_processors.static' to the list of context processors did fix your problem because as you can now see, it is inserting the value for STATIC_URL wherever it sees {{ STATIC_URL }} in your templates. The error is that you've changed the value of STATIC_URL to "/home/user1/djangoblog/blog/static/" probably because you've been confused by some of the answers here.
Change the value of STATIC_URL back to '/static/' so that line should read
STATIC_URL = '/static/'
That will fix your problem.
Django templates simply put whatever is in the variable into the template. They don't care what it is or what it represents. If the value of STATIC_URL is /home/user1/djangoblog/blog/static/ then it dutifully inserts /home/user1/djangoblog/blog/static/ wherever it sees {{ STATIC_URL }} which is why you are seeing
<img src="/home/user1/djangoblog/blog/static/images/a.jpg" />
whenever it renders the template containing <img src="{{ STATIC_URL }}images/a.png" />