Django Static Files CSS - django

How can I view my static css files? I've set my STATIC_ROOT, and am using python manage.py runserver.
In my development environment, according the docs, I only need to place my static files (in this case, /static/css/typography.css) in my STATIC_ROOT, and python manage.py runserver will automatic create the views necessary to access it if I have DEBUG = True.
STATIC_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), "static")
I've also tried manually adding the views in URLConf, which won't display the css file either:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf goes here ...
urlpatterns += staticfiles_urlpatterns()
In my template, the {{ STATIC_URL }} gets to the correct address (/static/css/typography.css), but it will not serve the file when I try to access it:
<link href="{{ STATIC_URL }}css/typography.css" rel="stylesheet" type="text/css">
Notes: The other Django related static files questions on StackOverflow are over two years old. Django version 1.3b1 differentiates STATIC (static files, such as css and images) and MEDIA (user-uploaded file).

Besides. all the tries mentioned above, you must also make sure that your template is receiving the RequestContext when called from the view.
http://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/
This link gives various ways of doing the same and you could choose any one. :) Also, the TEMPLATE_CONTEXT_PROCESSORS must be added to settings.py for this to take effect.
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"myapp.processor.foos",
)
Note: STATIC_ROOT is the place where all your static files are stored by Django after collecting them from STATICFILES_DIRS.
Runserver will pick them up from the path mentioned in STATIC_ROOT, so STATIC_URL should point to the same location as STATIC_ROOT.

Answered here: Django staticfiles app help
I was putting my files in STATIC_ROOT, so adding this works:
STATICFILES_DIRS = (STATIC_ROOT,)

In development:
#settings.py have this by default
STATIC_URL = '/static/'
This means when you want to use static files, django will look for them in folder 'static' in your app directory. So you need to create folder 'static' in every your app and put inside your static files.
In production:
1. Make place to hold static files from all app's
STATIC_ROOT = "/var/www/example.com/static/"
2. Run python manage.py collectstatic to collect static files from all app's in STATIC_ROOT folder.
3. In settings.py change DEBUG=False and ALLOWED_HOSTS = ['yourhostadress'].
4. Point your webserver to STATIC_ROOT folder (eg. for Apache2.4):
Alias /static/ /path/to/mysite.com/static/
<Directory /path/to/mysite.com/static>
Require all granted
</Directory>
After this setup, your django project should be able to run (using mod_wsgi) and use static files on Apache web server.

Related

Difference between static files and media files: How to show some upload image in template

I am new to Django and still struggling to grasp static files and media files.
IF i want have images that are stored in models with mode.FilePathField on my website that are static then how should i call them properly in my templates:
using static tag Like that:{% static project.image.path %}
or that just by calling it: {{ project.image.path }}
When reading tutorial i got answers that the first one but then it doesn't work. It gives me wrong paths
i will get 'static/MyApp/static/Myapp/img.jpg' instead of MyApp/static/Myapp/img.jpg
I would be really glad for an example of static files called dinamacally.
According with django doc here
Web App generally need to serve additional files such as images, JavaScript, or CSS. In Django, he refer to these files as static files. Django provides django.contrib.staticfiles to help you manage them.
On the other hand files which are uploaded by the user are called Media or Media Files.
a - When you want to serve static files that's what you have to do first:
1- Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS
2- In your settings.py file of your project, define STATIC_URL const like this: STATIC_URL = '/static/'
3- In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE as follow:
{% load static %}
<img src="{% static 'my_app/example.jpg' %}" alt="My image">
4- Store your static files in a folder called static in your app. For example my_app/static/my_app/example.jpg.
5- In developpement you must add following snippet:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
B - Now When you want to serve media files you have to do this:
1- Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS
2- In your settings.py file of your project, define MEDIA_URL const and MEDIA_ROOT const like this:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
3- In developpement server you must add following snippet:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
4- inside your template i you have to get your media files (Example show your image) you must use url attribut of your model filefield:
<img src="{{app_model.model_file_field.url}}" other attribute >

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 missing when rendering template

I am using django 1.3 and trying to deploy a django project (client sent) on my dev machine (ubuntu 12.04). The problem is regarding the static files. My directory structure is as follows:
project_name
media
static
css
img
js
settings.py
Here is my settings.py:
ROOT = '/home/user/project_name'
MEDIA_ROOT = '%s/media/' % ROOT
MEDIA_URL = '/media/'
STATIC_ROOT = '%s/static/' % ROOT
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
My site is perfectly deployed but the css, js and imgs are missing. Same is the case for the admin interface. When I use the link http://mysite.com/static/js/some.js it gives a 404.
Help would be appreciated and up-voting an answer is custom.
I think you need to run ./manage.py collectstatic :)
You don't mention configuring your web server to actually serve the static files. You need to point it at the directory that collectstatic put them into.
did you run python manage.py collectstatic ? see here
be careful that in production you should place the static file in a static server. There should be something in the guidelines.
And a little offtopic..
It will be better, to use:
MEDIA_ROOT = os.path.join(os.path.dirname(file),'media').replace('\','/')
STATIC_ROOT = os.path.join(os.path.dirname(file),'static').replace('\','/')
and in main urls.py at development, django webserver only:
urlpatterns = patterns('',
(r'^media/(?P.*)','django.views.static.serve',{'document_root': os.path.join(os.path.dirname(file),'media').replace('\','/') }),
(r'^static/(?P.*)','django.views.static.serve',{'document_root': os.path.join(os.path.dirname(file),'static').replace('\','/')}),
In this way, u dont need collectstatic, ull need it at production server, where u will use nginx or something other to server your static

How to use django-cumulus for serving Static files?

I'm trying to use django-cumulus for serving files off Rackspace CloudFiles. I'm currently only trying it on my local dev server, using Django 1.4.2.
I can use cumulus's syncstatic management command to upload all my static assets successfully, but I can't seem to display them on my site with the same settings.
If my relevant settings are:
STATIC_URL = '/static/'
CUMULUS = {
'USERNAME': 'myusername',
'API_KEY': 'myapikey',
'CONTAINER': 'mycontainername',
'STATIC_CONTAINER': 'mycontainername',
}
DEFAULT_FILE_STORAGE = 'cumulus.storage.CloudFilesStorage'
STATICFILES_STORAGE = 'cumulus.storage.CloudFilesStaticStorage'
then when I run syncstatic all my apps' static files are uploaded into /mycontainername/static/, as I'd expect. But when I load a page in admin it ignores STATIC_URL and tries to serve assets from URLs like http://uniquekey....r82.cf2.rackcdn.com/path/to/file.css rather than http://uniquekey....r82.cf2.rackcdn.com/static/path/to/file.css.
Also, I can't see how to have my public (non-admin) pages use the static files on CloudFiles, rather than serving them from a local /static/ directory.
Have I missed some crucial setting, or am I doing something else wrong?
I had the same problem. What i did was to
git clone https://github.com/richleland/django-cumulus.git
edit context_processors.py
from django.conf import settings
from cumulus.storage import CloudFilesStorage
def cdn_url(request):
"""
A context processor to expose the full cdn url in templates.
"""
cloudfiles_storage = CloudFilesStorage()
static_url = '/'
container_url = cloudfiles_storage._get_container_url()
cdn_url = container_url + static_url
print {'CDN_URL': cdn_url}
return {'CDN_URL': cdn_url}
Once you are done, install it with sudo python setup.py install
Do note that context_processors.py from django cumulus is actually quite slow

django and static css plus js files

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