django and static css plus js files - django

i did a small app on django and it is using templates. Each tempalate use static files such as css, js and images. all those files in same directory as template.
template
main.html
support.html
about.html
...
css
reset.css
style.css
...
img
js
jquery.js
main.js
...
if there is was to configure django development server to load those files without editing html templates files?
i am receiving
http://127.0.0.1:8000/face/css/960_24_col.css 404 NOT FOUND 127.0.0.1:8000
this changes in settings.py didnt help me
STATIC_ROOT = 'C:/Projects/site/website/face/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = ('C:/Projects/site/website/face/static',)

You might want to use the contrib app staticfiles. At the bottom of the doc page you'll see how to use it on development server.

STATIC_URL has been defined as '/static/' so all static files will be served from /static.
In other words /face/css/960_24_col.css is incorrect.
This should be /static/face/css/960_24_col.css , assuming the face directory is located at C:/Projects/site/website/face/static/face.
Might I also advise you not to use absolute paths in your settings file. To find out the absolute path of the root of your project use something like:
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))

Here is how I serve static files via the Django dev server.
Defined in urls.py:
from os import getcwd, path as ospath
...
urlpatterns += patterns('',
(r'css/([a-zA-Z0-9_.]+.css)$', 'django.views.static.serve', {'document_root': ospath.join(getcwd(), 'css')}),
(r'images/(.*)$', 'django.views.static.serve', {'document_root': ospath.join(getcwd(), 'images')}),
(r'js/([a-zA-Z0-9_.]+.js)$', 'django.views.static.serve', {'document_root': ospath.join(getcwd(), 'js')})
)

Related

Serving Static files on AWS Django application

I know that this isn't the first time the question has been asked, so I'm apologizing up front. I've been working on this for a few days and still have no clue how to proceed.
I followed this tutorial to the tee: https://aws.amazon.com/getting-started/hands-on/deploy-python-application/
The website is up and running, but of course the static files won't load.
Here's where I'm at. In settings.py, I've set my STATIC_ROOT and STATIC_URL to the following:
STATIC_ROOT = os.path.join(BASE_DIR, 'mysite', 'static')
STATIC_URL = '/static/'
I ran collectstatic and gathered all my static files into the mysite app directory. It looks like this:
-mysite
- mysite (app)
- static
- base
- base.css
- settings.py
- urls.py
- wsgi.py
Unfortunately, the static files still fail to load on the website.
Here are my questions:
Suppose I wanted to view the base.css text file on the web. Would I go to www.mysite.com/static/base/base.css? If no, what would the URL be? If yes, why is it not appearing given the current set up?
Per the AWS tutorial, I ran edited the httpd-app.conf file to include the following
Alias /mysite/static /opt/bitnami/apps/django/lib/python3.7/site-packages/Django-2.2.9-py3.7.egg/django/contrib/admin/static
What was the purpose of the edit? How does it impact how the static files are served on the site?
Any help you guys can offer on loading these static files will be a lifesaver.
Your urls.py file needs to be configured to serve your STATIC_URL
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
More on serving static files with Django

django static files cannot be found

In my settings file i have the following
STATIC_URL = '/static/'
my app name is reg_service
So my directory structure is like reg_service/reg_service/settings.py
And i have the static directory in reg_service/static/js
reg_service/manage.py
reg_service/reg_service
reg_service/templates
But in my template if i include the following script the result is "GET /static/js/jquery.min.js HTTP/1.1" 404 1652 whats is wrong here
<script src="{{ STATIC_URL }}js/jquery.min.js"></script>
The idea of django is that you should serve your static files directly through your web server.
For development purposes you can 'trick' django to serve the static files themself:
urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Django will find your static files, and serve them under the url defined under STATIC_URL.
That's not very performant nor secure, but works ok for development. For production you should configure your web server (Apache, Nginx, whatever) to serve the files directly under the url defined in STATIC_URL.
For more information see: https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-during-development

Static Files With Django 1.6

I have spent all day and nothing works. I have seen at least 20 posts here about the same topic and they are different with different suggestions and nothing works for me.
Running Django 1.6 with Python 2.7.+
I'm trying to load the css for the polls app from the django tutorial.
project layout
Project
|-polls
|-static
|-polls
style.css
|static
here is the settings.py
STATIC_URL = '/static/'
STATIC_ROOT = '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/static'
template code
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">
urls.py
urlpatterns = patterns(...)+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
polls/urls.py
urlpatterns = patterns(....,url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/'}),)
After running: python manage.py collectstatic, everything is collected and static folder which is on root gets populated accordingly with the admin and polls folders and files.
I start the server: python manage.py runserver everything works fine except the css is not loaded
this is what i get from the Chrome console when i inspect the html
....
<link rel="stylesheet" type="text/css" href="/static/polls/style.css">
....
which looks fine but gives the following output
[16/Nov/2013 00:44:41] "GET / HTTP/1.1" 404 2141
[16/Nov/2013 00:44:45] "GET /polls/ HTTP/1.1" 200 820
[16/Nov/2013 00:44:45] "GET /static/polls/style.css HTTP/1.1" 404 1649
Any help would be appreciated. I followed everything step by step. I don't know what to do anymore
UPDATE
DEBUG=True
full urls.py
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from PoolsDjangoProject import settings
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'PoolsDjangoProject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^polls/', include('polls.urls', namespace='polls')),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
full polls/urls.py
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(),name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote', name='votes'),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/'}),
)
And when i try to access
http://127.0.0.1:8000/static/polls/style.css
I get
Page not found (404)
'polls/style.css' could not be found
I found it necessary to restart the running server after following the steps in
https://docs.djangoproject.com/en/1.6/intro/tutorial06/#customize-your-app-s-look-and-feel
in order to pick up the newly created static directory. That step isn't listed in the tutorial. I have opened a ticket requesting its addition.
I realise this answer is not likely to help your specific case but this question comes up prominently in Google when searching for problems with adding a static directory to the example Polls app.
I ran into this problem too. My problem was that I didn't have my main app in the installed apps, whatever folder that has wsgi.py in it, that needs to be in INSTALLED_APPS.
I struggled with this problem as well.
Here's how I solved it (DEBUG=True):
After creating a project and several apps, I created a directory called "static" that sat alongside my app directories (same level as .manage.py).
I set my static URL to '/static/' in settings
I set my static root to STATIC_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../static/').replace('\\','/')) (BASE_DIR = os.path.dirname(os.path.dirname(__file__)))
I set my staticfiles dirs to STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), '/Users/username/sites/containing_dir/project_dir/static/',) (assumes OSX path)
I added + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to my urls.py for my project
My static media is now served from http://127.0.0.1:8000/static/css/styles.css (assuming runserver command).
Comment if you need addition description!
Firstly it has to be known that Django is not responsible for serving static files on production servers. However, it does serve them when DEBUG=True during development for the sake of debugging.
For serving static files when debug=true you have to do nothing. I don't know why it is creating confusion among newbies on how to setup it. The below should help you create static files for both production and dev modes clearly
Development mode : when DEBUG=True
create your project django-admin.py startproject mysite
create your app manage.py createapp myapp
Add myapp to INSTALLED_APPS in settings.py
In myapp dir, create a folder static
In the myapp/static dir, save a file myfile.css
In settings.py, provide a valid address to STATIC_ROOT folder to store static files. It could be something like os.path.join(os.path.abspath(os.path.dirname(__file__)), "mystatic") if you want to store your collected files at mysite/mysite/mystatic.
run manage.py collectstatic; now you have to see the static file collected at the directory you mentioned above..It should also create one if its not present. You are free to put any directory.
test the url http://127.0.0.1:8000/static/myfile.css
In case if its not working yet, try restarting the site.. New files are not recognized dynamically!

Django on Heroku - Broken Admin Static Files

I have a Django app running on Heroku/Cedar, configured as per the instructions at https://devcenter.heroku.com/articles/django
Using gunicorn as per Heroku's instructions fails to include the static files required for Django's admin to function. I can change the Procfile to "manage.py run_gunicorn" for local development, but that doesn't fly on Heroku.
I've searched all over for a fix - is there some way to include the admin static files without throwing them on S3 with my other static files?
If you use runserver and configure your app with DEBUG=True, then it will serve the admin files just like on your development machine. However, this is definitely not the recommended way to do it, and I would suggest that you put them on S3.
Using the django-storages app it's very easy to configure collectstatic to automatically push all the admin files to S3. You can find directions here
Check out this post: http://matthewphiong.com/managing-django-static-files-on-heroku
If that doesn't work for you try adding the following to your urls.py after the normal url pattern tuple. Make sure you have your STATIC_ROOT set and you've run collect static on your local environment all before pushing to heroku.
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
just add these instead
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
using django 1.4.1
It seems little late compared to the asked date. But I got into this issue and spent 30 mins on what I did wrong. So here it is the magic solution for those who might fall in this trap.
There is some problem with Heroku's django.contrib.staticfiles.urls
SOLUTION
You need to install dj-static (Link to download) on your Heroku setup.
It's a Django middleware utility that allows to properly serve static assets from production with a WSGI server like Gunicorn.
I hope this will help someone.
create 'static' folder into your 'project_directory'.
set the 'STATIC_ROOT' path in 'settings.py' file which can serve your admin-site's static files.
STATIC_ROOT = (os.path.join(os.path.dirname(__file__), '..', 'static'))
Add STATIC_ROOT in '/urls.py'
from django.conf import settings
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
Run the following command that will copy all the admin static files into project's static folder.
python manage.py collectstatic
Now do git add, commit and push heroku master.
If you are deploying to Heroku without using whitenoise (which I would suggest), definitely use dj_static https://pypi.python.org/pypi/dj-static!
I spent the past 3 hours trying to serve my files to heroku and dj_static worked within a matter of 2 minutes.
I got django admin working with following edits
urls.py(at the end)
import settings
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
Procfile
web: gunicorn hellodjango.wsgi -b 0.0.0.0:$PORT
'django.contrib.staticfiles.views.serve'
instead of
'django.views.static.serve'
Follow this to fix all static related issues with Django and heroku.
In your settings.py paste this at the end
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR,'templates'),
)
STATIC_URL = '/static/'
Your template for a particular app should be in app_name/templates/app_name/
When you render template this is how you will specify template name
in views.py
.....
return render(request,'app_name/template_name.html',context)
For static files place your files here:
project_folder/app_name/static/app_name/css
project_folder/app_name/static/app_name/js
project_folder/app_name/static/app_name/img
to access your static file use path app_name/css/style_name.css
If you follow this, all your static files will load up fine in heroku as well as in your local development machine.

Django: Problem with template paths?

So after a few hours of irritation i finally got my django site up and running! The only problem i have now is that all the stylesheets/images are linked incorrectly. Or, well, they are linked correctly but django wont give me the files, kind of.
This is how it's set up:
views.py:
from django.shortcuts import render_to_response
def home(request):
return render_to_response('index.html')
urls.py:
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
# Examples:
url(r'^$', 'mysite.views.home', name='home'),
)
and that brings up index.html, but none of the other files are shown, like images, stylesheets etc. How do I solve this? I have a feeling it's really easy!? I tried googling, but couldn't find anything.
Thanks in advance,
qwerty
It sounds like what you're looking for is the ability to serve static files.
Basically, you'll need to add a folder somewhere in your project to save the media to. Then, you'll need to edit your urls.py and settings.py files to accommodate access to your new static media directory.
urls.py
urlpatterns = patterns('',
# Examples:
url(r'^$', 'mysite.views.home', name='home'),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root':
settings.STATIC_ROOT}),
)
settings.py
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
# Should be the location where you put your static folder.
# Should be different for testing and production environments.
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'media')
# This is assuming that your settings.py file is in path/to/project/ and your
# static files are in path/to/project/media/
Then in your template you can do this:
< img src="/static/my_image.jpg" / >
Or whatever you want. This will work for javascript, css and image files.
Expanding on Shamanu4's comment: what you're asking for is how static files are served. For development purposes, you can use the static file server.
Long term, though, this is not an optimal solution. The easy way is to segregate all your static files and serve them directly through your web browser via a different path. In Apache, this static file path can be inside your Django path if you configure the static path first.
If you need high performance, though, the Django team recommends that you use a lightweight, speed-optimized server (such as lighttpd) to serve static files and another server with WSGI support (such as Apache) to serve Django.
In the Django project I have at work, I have Django served from /djangoprojname/ and static files served from /djangoprojname/static/. On disk, the static directory is at the same level as my Django project's directory. both of which are in a Mercurial repository. Within static/, I have css/, js/, and img/, and within those directories, I have one directory per app, named the same as the app. This keeps things from getting messy.
My django.conf (in /etc/httpd/conf.d on Fedora or RHEL) looks something like:
WSGIDaemonProcess djangoprojname threads=15
WSGISocketPrefix /var/run/wsgi/wsgi
Alias /djangoprojname/static/ /var/www/djangoprojname/static/
Alias /djangoprojname/admin/media/ /usr/lib/python2.6/site-packages/django/contrib/admin/media/
WSGIScriptAlias /djangoprojname /var/www/djangoprojname/django.wsgi
WSGIProcessGroup djangoprojname
<Directory /var/www/djangoprojname>
Order deny,allow
Allow from all
</Directory>
<Directory /usr/lib/python2.6/site-packages/django/contrib/admin/media>
Order deny,allow
Allow from all
</Directory>
For development, I added this to the end of my project's urls.py:
# Only serve static media if in development (runserver) mode.
if settings.IS_DEV:
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT,
'show_indexes': True}),
)
settings.IS_DEV is set in my settings.py to True if this is running on a development server. manage.py is modified to set an environment variable if runserver is used, and settings.py checks for this variable. MEDIA_ROOT is set to the path to the static directory.
You are probably having problem with MEDIA_ROOT and MEDIA_URL in your settings.py. Please refer to http://docs.djangoproject.com/en/1.3/ref/settings/#media-root