Here's the code I have:
In the HTML file:
<link rel="stylesheet" href={% static 'css.css' %}" >
In settings.py:
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
The css.css file is located in the static directory which is in the same directory as manage.py ,
So why isn't the css file loading?
There is also a js file which doesn't seem to be loading either, and it's in the same directory as the CSS file and I'm loading it in with the same method as the CSS file.
Also, my pc isn't currently connected to WiFi, in case it makes a difference. I'm working with localhost.
Have you configured your Static files URL.
According to best practice
STATIC_URL = '/static/'
Actually the above is too little information to help anyway. Can you tell us the application environment (production/development) etc because there are specific configurations for each in Django. Also please provide code using the code markup. Assuming you are using Django 1.11, read this for a better understanding or better yet see a tutorial for beginners
Here's the file structure i am using
-----+root
----------+app
--------------+common
--------------+config
--------------+controllers
--------------------------+rootPage.js
----------+public
--------------+rootPage.jade
----------+server.js
Here's my jade file
doctype
html(lang = 'en')
head
title PlanUrNight
meta(charset = 'utf-8')
link(rel = 'stylesheet' href = '//maxcdn.bootstrapcdn.com/bootswatch/3.3.0/flatly/bootstrap.min.css')
link(src='//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js' rel = 'stylesheet')
link(rel = 'stylesheet' href = './css/rootPage.css')
body
nav.navbar.navbar-inverse(role= 'navigation')
.navbar-header
button.navbar-toggle.collapsed( type='button', data-toggle='collapse', data-target='#navbar-inverse', aria-expanded='false', aria-controls='navbar')
span.sr-only Toggle navigation
span.icon-bar
span.icon-bar
span.icon-bar
a.navbar-brand(href='#') PlanUrNight
.collapse.navbar-collapse#navbar-inverse
ul.nav.navbar-nav
li: a( href="#") Home
.collapse.navbar-collapse.navbar-right
.facebook-login-wrapper
a.btn.btn-primary(href='/auth/facebook') Facebook
span.fa.fa-facebook
.container-fluid
.row
.col-md-8.col-md-offset-2.main-container
.images-container
img.drink(src='img/drinking.png')
img.dance(src='img/couple_dancing.png')
img.club(src='img/club_ball.png')
.row
.col-md-2.col-md-offset-6.search-container
span.glyphicon.glyphicon-search
.input-group
input.form-control(type='text', placeholder='Search')
script( src='//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js' type='text/javascript')
script( src='./controllers/rootPage.js' type='text/javascript')
I have tried multiple variations of the source, but it just doesn't seem to be loading the JavaScript file. Each time I get an error log in my console, saying Error 404: rootPage.js not found
I am using express with node, and in my server.js file I have the following line for serving static files
app.use(express.static(__dirname+'/public'));
So what am I doing wrong here? Does the usage of the app.use line above change the root of my directory in some way so that I need to change the file path to access my JS files?
Or is there a different way to load JS files in Jade?
Your file organization is a bit wonky. Based on the one middleware you showed us, all files in the /public folder will be served as-is, but no static files elsewhere will be.
Generally, jade files that you're rendering with server logic are in a /views folder which is not served directly, but instead available to server side route handlers or controller logic to call res.render with.
So if you have clientside JS files you want to serve as static content you need them either under the /public folder or create more static middleware calls to point to whatever folder they are in.
/** Edit after first two comments **/
Sorry for not providing more examples, etc before, I was on my phone.
Wonky is perhaps a harsh term and I'm sorry. What I meant was it doesn't really match the standard layouts I've seen. There's a few ways to do it, but most small(ish) Express projects at least start out with the template generated by the express command line tool.
In that case, all the stuff in your ./root/app directory would be server-side code that doesn't get directly served to the client ever. Most of the sites I've seen (exception being the default template from the MEAN.js project) follow a pattern something like this:
app
- errors
- models
- controllers
- routes
- views
public
- css
- js
- img
package.json
server.js
Sometimes there's a lib folder that's a peer of app where you put utility stuff. 'views' is where all the jade templates live.
Everything in the public folder is exposed via a single middleware like you did:
app.use(express.static(__dirname+'/public'));
Everything else will not get served as static files. If you have a clientside JS structure that uses an MVC pattern, you'd then have model, view, and controller folders under ./public/js
The MEAN.js folks take a different approach, making each logical component of the app (e.g. user management, etc) into a module and then organizing each module as folders that look like ./<module name>/server and ./<module name>/client with structure for models, controllers, etc, under each of those depending on if it's server code or client code.
You're correct on how to add more more static middleware.
Try
script( src='./app/controllers/rootPage.js' type='text/javascript')
Background info: django 1.6.2, python 2.7.5
I recently started applying internationalization to my django project. I've managed to make it work in the models, views, and templates of an app (called metrics). However, when I try to apply internationalization on the static js files, gettext() does not seem to work since it always returns the string that I pass to it, ignoring the browser language. On the other hand, the {% trans ... %} tags in the html template (which uses those js static files) get translated correctly. This indicates that the issue resides in the internationalization of my js static files. Could anybody offer any guidance or suggestions?
This is a summary of my project configuration:
In the project settings I included:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
LANGUAGES = (
('es', _('Spanish')),
('en', _('English')),
)
LOCALE_PATHS = (
os.path.join(BASE_DIR,'locale'),
os.path.join(BASE_DIR,'metrics/'),
)
USE_I18N = True
USE_L10N = True
The djangojs.po and .mo files concerning the js static files are located in the locale folder sitting in my root directory while the django.po and .mo files sit in the locale/es/LC_MESSAGES folder within my app. I ran django-admin.py makemessages -l es and django-admin.py makemessages -d djangojs -l es from the appropriate directory and django-admin.py compilemessages from both (even though that may be redundant...). Note that the .po files have no FUZZY tags.
In the project's url.py file I included:
js_info_dict = {
'packages': ('metrics',),
}
urlpatterns = patterns('',
url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
...
)
Perhaps this part is wrong since my djangojs.po and .mo files are in the root directory, but I tried locating them in my app directory and it did not work either.
Finally, an example of gettext use in my static js file (using d3js):
svg.append("g").append("text")
.attr({"x":0,"y":17})
.style({"text-anchor":"middle","fill":"black"})
.text(gettext('Schedule'));
Any suggestions? And sorry about the huge write-up but I am trying to provide as much info as possible.
I would like to use an alternate static directory for admin's static directory. The links for javascript and css as used in the admin app show /static/admin/js or /static/admin/css in the uri.
I have copied over the static/admin directory to /Users/username/django_project/django_app/ directory. How can I now tell my app in the settings.py to use /Users/username/django_project/django_app/static instead? I realize this is not very good practice for production but am only interested in making some adds/changes to css and javascript so that it doesn't affect my django library for the Python environment I am using here.
Thanks!
You can now backup or move your static/admin directory and replace it with a symlink to new admin static path:
mv /static/admin /static/admin_old
ln -s /Users/username/django_project/django_app/static /static/admin
I know this has been asked before, but I'm having a hard time setting up JS on my Django web app, even though I'm reading the documentation.
I'm running the Django dev server. My file structure looks like this:
mysite/
__init__.py
MySiteDB
manage.py
settings.py
urls.py
myapp/
__init__.py
admin.py
models.py
test.py
views.py
templates/
index.html
Where do I want to put the Javascript and CSS? I've tried it in a bunch of places, including myapp/, templates/ and mysite/, but none seem to work.
From index.html:
<head>
<title>Degree Planner</title>
<script type="text/javascript" src="/scripts/JQuery.js"></script>
<script type="text/javascript" src="/media/scripts/sprintf.js"></script>
<script type="text/javascript" src="/media/scripts/clientside.js"></script>
</head>
From urls.py:
(r'^admin/', include(admin.site.urls)),
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'media'})
(r'^.*', 'mysite.myapp.views.index'),
I suspect that the serve() line is the cause of errors like:
TypeError at /admin/auth/
'tuple' object is not callable
Just to round off the rampant flailing, I changed these settings in settings.py:
MEDIA_ROOT = '/media/'
MEDIA_URL = 'http://127.0.0.1:8000/media'
UPDATE: I made some changes, but it's still not working:
settings.py:
ROOT_PATH = os.path.normpath(os.path.dirname(__file__))
urls.py:
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(settings.ROOT_PATH, 'site_media')}),
index.html:
<script type="text/javascript" src="/media/JQuery.js"></script>
<script type="text/javascript" src="/media/sprintf.js"></script>
<script type="text/javascript" src="/media/clientside.js"></script>
Filesystem:
mysite/
site_media/
JQuery.js
sprintf.js
clientside.js
__init__.py
settings.py
manage.py
-- etc
myapp/
-- app files, etc
When I go to a url like http://127.0.0.1:8000/media/sprintf.js, I get:
Page not found: /media/sprintf.js
But does that /media/ global directory exist? And have you placed in there a scripts subdirectories with the scripts you want to serve from there? What about the /scripts/... url from which you want to serve JQuery.js -- that doesn't seem to be served anywhere from your urls.py. If you (for whatever reason) want to serve scripts (or any other statically served file) from several different URL paths, all of those URL paths need to be matched in urls.py with the static-serving -- or else, do the normal things and serve them all from the /media/... root URL, and map that media root to the dir where you actually keep these files (in their respective subdirs, typically).
Django's docs about static serving (for development only, since it's documented as
Using this method is inefficient and
insecure. Do not use this in a
production setting. Use this only for
development.
so beware!-) seems pretty clear to me.
You may want to use absolute path for 'document_root' in urls.py if you want to use the development server to serve static files. MEDIA_ROOT and MEDIA_URL don't play any role here.
Here are my settings for your reference. I put all static media files under site_media/
mysite/
site_media/
css/
js/
images/
...
in settings.py:
ROOT_PATH = os.path.normpath(os.path.dirname(__file__))
in urls.py:
url(r'^media/(?P<path>.*)$', "django.views.static.serve", {'document_root':
os.path.join(settings.ROOT_PATH, 'site_media')})
You can move static files else where, just need to point 'document_root' to the correct path. Make sure comment out this url line for production deployment.
Actually, you can put your Javascript files (and all your static content) anywhere you want. I mean, Django does not impose a standard on where to place them, after all they won't be handled by Django, they'll be served by the webserver.
Said that, It's a good idea to keep them somewhere close to the project's files. I'd recommend to keep them in a sibling folder to your Django code. Same with MEDIA_ROOT.
It is a good idea to decouple your static files from python files because now you can put them in totally separate folders in a production environment and easily give different access to static files and python code (say FTP access, or permissions).
Something to keep in mind is that the settings' MEDIA_ROOT is the place where user's media files (that is uploaded content) will be placed, these are not your static project files, these are whatever files your Django app uploads (avatars, attachments, etc).
Proposed folder structure:
mysite.com/
media/ - User media, this goes in settings.MEDIA_ROOT
static/ - This is your static content folder
css/
js/
images/
templates/
project/ - This is your Django project folder
__init__.py
manage.py
settings.py
myapp/
__init__.py
...files..py
See the other responses recommendation on using Django's serve() function for development enviroment. Just make sure you add that url() to your urlpatterns under a settings.DEBUG is True conditional.
As for your templates, it's a good idea to use a context processor to send your static file's path to all your templates.
I serve javascript via static. So I have something in my urls.py like
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.getenv('STATIC_DIR')})
So JS urls look like /static/js/blah.js, CSS urls look like /static/css/blah.css, etc. I have Apache handle the static directory when running in production to avoid any issues with Django's static serving mechanism.
For my development work, I use Django's built-in server, but I read the media files from the same directory as they would be in production (/srv/nginx/sitename/media/). So I clone the exact directory structure of my production server on my computer at home, letting me seamlessly push changes to production without having to change anything.
I keep two different settings.py files, though. My home settings.py file has my local database settings, a different MEDIA_URL setting, and DEBUG set to True. I use this in my URLs file to enable the server view for local media (since I don't run nginx on my home computer).
In urls.py:
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
From settings.py (note, MEDIA_ROOT must be an absolute path):
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = '/srv/nginx/<sitename>/media/'
# 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/"
MEDIA_URL = 'http://127.0.0.1:8000/media/'
TEMPLATE_CONTEXT_PROCESSORS = (
# I've taken out my other processors for this example
"django.core.context_processors.media",
)
In a template:
<link rel="stylesheet" href="{{ MEDIA_URL }}css/form.css" />{% endblock %}
Filesystems:
/srv/nginx/<sitename>
/media <-- MEDIA_ROOT/MEDIA_URL points to here
/css
base.css
form.css
/img
/js
Oh, also: if that's a direct copy from your urls.py file, you forgot a comma after your serve view, that's causing your TypeError ;)
The error 404 occurs because MEDIA_ROOT requires absolute path, not relative. The server is trying to access /media in your filesystem, which is obviously not what you want.
Try this instead:
import os
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'site_media')
MEDIA_URL = '/media/'
This is a structure I use in a project separated into multiple apps. It's a good practice to adapt this structure right at the start -- you don't want global rearrangement when you need to add another app to your project.
/media
favicon.ico
robots.txt
/upload # user uploaded files
/js # global js files like jQuery
/main_app
/js
/css
/img
/other_app
/js
/css
/img
Then I use excellent StaticMiddleware from django-annoying to serve files. settings.py:
import os
import annoying
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), "media")
MIDDLEWARE_CLASSES = (
'annoying.middlewares.StaticServe',
#...
)
I just remove the '^',
"r'static/" instead of "r'^static/".
It's works for me ,good luck.
url(r'static/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': the_path }),