When I use MEDIA_URL or STATIC_URL to point to /static/ currently set MEDIA_URL to /static/
and using it in a path to CSS file like:
<link rel="stylesheet" type="text/css" href="{{MEDIA_URL}}css/css.css" />
It points to /static/css.css, but trying http://localhost/static/css.css gives 404 error.
I have in settings:
.....
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/static/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = 'D:/programming/django_projects/ecomstore/'
.....
In urls.py I have point to static like this:
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root':'D:/programming/django_projects/ecomstore/'}
So where problem is? Why it is showing 404, do I need to create some view for static files? Or is there some thing else wrong in my settings or urls.py ? Any response will be appreciated, as I am newbie in django.
thanks in advance
You need to re-read the docs more closely: https://docs.djangoproject.com/en/dev/howto/static-files/
Here's some things to note:
MEDIA_URL and MEDIA_ROOT are for user uploads (FileFields and ImageFields on your models). It should be its own folder; "media" is common.
STATIC_URL and STATIC_ROOT are for your static resources. It should also be its own folder; "static" is common.
Do not actually put anything in STATIC_ROOT. This directory is only for the output of the collectstatic management command in production.
Your static resources should go in your apps' "static" folder or a completely new and different directory (i.e. not MEDIA_ROOT or STATIC_ROOT). You then add the path to that directory to STATICFILES_DIRS.
Don't add anything to urls.py. In development, Django will automatically serve anything in your apps "static" directories or any directory in STATICFILES_DIRS. In production, your webserver will be responsible for serving these files.
Related
Settings.py file in Project directory :
I already added following :
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
-> in template
<script src="{% static "validateurl/home.js" %}"></script>
I have a directory static under project directory. home.js is under validateurl directory under static.
Referring JS File using following in template html file :
Please advise what am I missing here.
Errors below :
Here are the steps to configure your django app to serve static files for local development.
The STATIC_ROOT default is None so you have to specify that in settings. Make sure you have something like this in your settings.py This tells your webserver where to find and serve the static file mapped to a url.
import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Second also specify your STATIC_URL variable as it also defaults to none. following should suffice. This will be used for setting up the urlpattern.
STATIC_URL = '/static/'
You need to have a url pattern so your server knows what url corresponds to the static files
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Specify STATICFILES_DIRS variable in settings. So that the collect static manager knows where to find statics and put them in the STATIC_ROOT. This can be an array or tuple of items to different directories. This can be empty if you have no additional directories
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'pathtohomejsdirectory/'),)
Finally, make sure you run python manage.py collectstatic
This copies all the files specified in STATICFILES_DIRS over to the /static/ (STATIC_ROOT) directory to be served by django.
On a production, you want your webserver/reverse proxy say nginx or apache to serve the files. See here django documentation here
I am working on a multi-app website. And I have bunch of noob questions.
My dir structure looks like as below:
/var/www/html/portal
src/
manage.py
portal/
static/
admin/
css/
img/
js/
fonts/
templates/
base.html
homepage.html
venv/
Is my dir structure as per as Django standards?
Are my STATIC files settings correct?
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Or should it be
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
Should I collectstatic after copying all my static files such as css,js etc or I can do it before copying files in those dirs?
If I do collectstatic without mentioning STATIC_ROOT I get an exception
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
But when I replace STATICFILES_DIRS with the following, my .css files stop serving. What am I doing wrong?
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
You don't need to run staticfiles when you're running a development server and DEBUG is set to True.
Static and media files can be then served directly via the web process (Docs) with adding these lines to your main urls.py:
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
As to the whole STATIC_URL, STATIC_ROOT, MEDIA_URL and MEDIA_ROOT, they're all related to how you'll serve your app in production, with a proper webserver.
What usually happens then is that the webserver (i.e. Nginx) handles serving files, not the Django app. But the Django app needs to know where are they. So:
STATIC_URL and MEDIA_URL need to be the same in your Django app settings and in your webserver config, for example with Nginx:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
...
location /static {
alias /home/myusername/myproject/static/;
}
location /media {
alias /home/myusername/myproject/media/;
}
STATIC_ROOT MEDIA_ROOT are 100% about how you want to structure your project on the server. Assuming the above, you need to work out how to point it to /home/myusername/myproject/static/.
Example of my settings:
BASE_DIR = Path(__file__).parent.parent.parent
MEDIA_URL = '/media/'
MEDIA_ROOT = str(BASE_DIR.joinpath('media'))
STATIC_URL = '/static/'
STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles'))
Media files will be directly uploaded to the MEDIA_ROOT, but notice that you need to somehow get the static files from your applications (which could be in a number of folders, a library you use can have some extra static files, Django Admin has then, etc.) to the folder that Nginx is pointed to (which should be the same as STATIC_ROOT). That's where collectstaticfiles comes in and copies all your static files to that directory.
In regards to directory structure, there are differences of opinion on how it should be set up. A quick google search can bring up some websites and discussions on Django project structures. I recommend reading some of the information to determine what is best for your and your project.
The Django documentation has a best practices page as well that is a good resource/reminder. Django Best Practices.
I mainly followed the Two Scoops of Django directory structure. The Two Scoops has helped me a lot in understanding this. My own twist looks something like this.
src/
app/
templates/
app_name/
base.html
other_pages.html
tests/
tests.py
app_files.py
static/
images/
css/
etc..
templates/
global_includes/
include_file.html
base.html
The collectstatic should not effect the serving of your static files during development. From what I have learned, collectstatic is more for when you are serving your static files during deployment from a separate server, or aws, heroku, etc. More info can be found here in the docs: Managing Static Files, staticfiles app, Deploying static files
I have learned that if my CSS files are not serving, it usually has something to do with my path. Chrome developer tools inspect element/console helps me with any path errors.
Have you added
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
to your your main urlpattern/urls.py?
Here is more information on serving files during development: Serving static files during development.
Lastly check that your BASE_DIR is following the correct path for your project. You may have to change it.
I hope this helps.
Remember that if you have DEBUG set to 'False' it will ignore the staticfiles setting because it is expected that your webserver will be serving this directly. This caught me out a few times until I realized I hadn't updated the staticfiles folder (which I keep in a separate repository for reasons I can't remember now).
This seems to work in current django (2.2) :
from django.conf.urls.static import serve
urlpatterns += [
path(settings.STATIC_URL[1:], serve, {'document_root': settings.STATIC_ROOT })
]
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to organize and load CSS within Django project/app?
I have follow several websites about how to setup static files in Django. Here are my steps.
Configure the setting.py:
STATIC_ROOT = '/Users/kin/mysite/static'
STATIC_URL = '/static/'
Run the collectstatic command:
python manage.py collectstatic
After that, I saw my image file is copied to the STATIC_ROOT.
Then in my template, I try to use my image file by:
<img border="0" src="{{ STATIC_URL }}images.jpg" width="304" height="228">
But there is no image when I load it on the browser. I checked the page source and STATIC_URL seems empty.
Can anyone shed some light here?
Thanks
Dont hard code the path in your setting. I usually put my static files in my main project, so my setting file look like this
import os
MAIN_PROJECT = os.path.dirname(__file__)
then
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
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.
os.path.join(MAIN_PROJECT, 'static/'),
)
After that, you can use {{ STATIC_URL }} in your view
Actually I got it right by just using the following code:
{% load staticfiles %}
<img border="0" src="{% static 'image.jpg' %}" width="304" height="228">
This will render the STATIC_URL path to me.
Thanks all for helping me out!
If you're running your app with python manage.py runserver then you may need to add the following to the end of your url conf (see docs).
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
The process for serving static files with django's dev server is different to the process for doing it with a production web server.
you can try with this
import settings in urls.py
and paste the below code in your urls.py
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'^static_media/(?P<path>.*)$',
'serve', {
'document_root': 'path/to/your/static/folder',
'show_indexes': True }),)
now go to your settings.py and change the setting like
MEDIA_URL = '/static_media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
now access your static file like
<link rel="stylesheet" type="text/css" href="{{MEDIA_URL}}css/header.css" />
I'm trying to configure Django to serve static files when using runserver (production works fine). Everything works fine for all of the static files that are under an apps directory. The problem comes with static files that are not under a specific app, but are in the final static directory. For instance, I have this project structure:
/myproject/
/myproject/static/
/myproject/static/css/foo.css
/myproject/app1
/myproject/app1/static/css/bar.css
urls.py
if settings.SERVE_STATIC:
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
)
urlpatterns += staticfiles_urlpatterns() # one of these may be redundant.
settings.py
SERVE_STATIC = True
PROJECT_ROOT = '/myproject'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(PROJECT_ROOT, 'static'),)
INSTALLED_APPS = ('app1',)
With these settings, I get the error:
ImproperlyConfigured: The STATICFILES_DIRS setting should not contain
the STATIC_ROOT setting
Which makes sense. I'm telling Django to collect static files, and put them in the same place - which could cause a loop.
If I comment out the STATICFILES_DIRS variable, django will find the static file 'bar.css'. But it does not find 'foo.css'.
If I comment out the STATIC_ROOT variable and put back the STATICFILES_DIRS, then it finds the file 'foo.css' - but of course, the 'collectstatic' command will no longer work.
Note - I realize that the '/static' directory is supposed to be empty, but the project I'm on, has files there anyway. :) As long as they're not overwritten by 'collectstatic', it looks like Django runserver should serve them - but it doesn't.
How do I serve the static files under STATIC_ROOT (such as foo.css) when running Django runserver?
Move the files that are in /static/ right now to a different directory -- call it /project-static/, for instance.
Then only include this line in urls.py:
urlpatterns += staticfiles_urlpatterns()
(remove the django.views.static.serve view)
And in settings.py, use this:
STATICFILES_DIRS = (os.path.join(PROJECT_ROOT, 'project-static'),)
Then you can put files in /project-static/ directory on your filesystem, the development server will serve them out of the /static/ URL prefix, and in production, collectstatic will find them and put them into the /static/ directory where the web server can find them.
I having some real trouble getting django to play nice with my media setup. I am not using staticfiles since I am have no need for a CDN at this point of the project and I want to keep it simple.
My folder structure looks like this:
/static
/admin
/css
/js
/etc
/css
/js
/images
The admin folder is a copy of the admin contrib media folder... since I am using mod_wsgi I know that this can't live in the django project folder.
My settings file:
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'static/')
MEDIA_URL = 'http://127.0.0.1:8000/static/'
ADMIN_MEDIA_PREFIX = 'admin/' (tried with leading slash too)
Urls:
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root':MEDIA_ROOT, 'show_indexes':True}),
No matter what I try, I can't get the admin media to serve. I know from reading the documentation that the ADMIN_MEDIA_PREFIX has to be very different from the normal media url, but I need to be able to serve the files outside of the system django folder because of mod_wsgi.
Can anyone help?
For your setup, ADMIN_MEDIA_PREFIX = MEDIA_URL + 'admin/' should work.