Reference static files in django in .py files ( NOT in templates) - python

I've been like an hour searching how to reference static files in django, but I only found how to do it in templates.
In my project, I succeeded in referencing static files in my templates, but I DON'T want to do it in templates, I want to do it in my .py files.
I think that i have to import static from somewere, I've tried with this:
from django.templatetags.static import static
from django.conf.urls.static import static
And trying to reference it like this
'<a href=/url> <img src="{{ STATIC_URL }}image.png" ></a>'
I've tried all possible combinations like
{% static image.png %}
{{static image.png}}
and so on...
Thanks!

from django.templatetags.static import static
'<a href=/url> <img src="{0}" ></a>'.format(static("image.png"))
Note that django.templatetags.static is actually a function. The template engine calls that function when you use the template tag.

If you want to find the actual file on disk, you can use the finders class of the staticfiles app:
>>> from django.contrib.staticfiles import finders
>>> finders.find("icons/exclamation.svg")
'C:\\<project folder>\\<project name>\\<app name>\\static\\icons\\exclamation.svg'
Django Docs

You can read django configuration to get STATIC_URL which contains URL base part for static files:
from django.conf import settings
import urlparse
print '' % urlparse.urljoin(settings.STATIC_URL, 'image.png')

Related

importing image to django page

I am trying to attach an image to my page (per https://docs.djangoproject.com/en/1.10/howto/static-files/#configuring-static-files), but it cannot be displayed: http://prntscr.com/evwern
settings.py
STATIC_URL = '/portfolio/'
urls.py
urlpatterns = [
url(r'^$', index, name='index'),]
index.html
{% load static %}
<img src="{% static '/catalog/static/portfolio/oh_i_ah.jpg' %}" alt="My image" style="width:640px;height:473px;"/>
Path to the image: mysite/portfolio/catalog/static/portfolio/oh_i_ah.jpg
If I try to open the image in the new tab it throws:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/portfolio/catalog/static/portfolio/oh_i_ah.jpg
1) You did not specify your app directory name. Need to know the app/directory name to answer your question properly.
2) You did not use 'static' properly.
3) You did not specify whether you are using default django development server or some production server. I am assuming that it's default django development server with DEBUG=True.
Solution
Let's imagine: You have an app named app0 (let's say you created that with "python manage.py startapp app0") and you have created a directory called "static " inside of that (following default django convention over configuration). Inside of this 'static' directory you have created another directory called 'app0'. So, you are going to put your file inside "/app0/static/app0". So, your file path becomes: "/app0/static/app0/oh_i_ah.jpg"
Now, set STATIC_ROOT properly in the settings.py
In the template file refer the file as {% static "app0/oh_i_ah.jpg" %} (without leading forward slash).
Now, everything will be ok.
Yes, you can put the static files outside of any app directory if you configure STATICFILES_DIRS, STATIC_ROOT in settings.py correctly.
Please properly describe your problem with as much details as possible so that we can help you in the right way.
in settings.py
import os
STATIC_URL = '/portfolio/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
and
python manage.py collectstatic
in index.html
{% load staticfiles %}
<img src="{% static '/portfolio/oh_i_ah.jpg' %}" alt="My image" style="width:640px;height:473px;"/>

Second static files directory in Django

I'm trying to create something like a photo gallery in Django. So far I'm working with the local Django copy and included web server and DB.
I'm done with most of the app logic but need to solve the static files problem. I need to have two locations - one for "media" which will be images and I expect to have them stored outside of the Django in future - now it's placed within Django root /files directory. So far I was able to make it working with the following:
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'files'),)
STATIC_URL = "/photos/"
index.html
{% load static from staticfiles %}
Photo
This works pretty well - when I click that link I can see picture stored at /files//picture.jpg being displayed as http://localhost:8000/photos/picture.jpg
But now I need to add some CSS and JS into that page and have no idea how to do that (besides placing them directly to /files directory which I need to avoid)
Thanks
You can fix this problem like this. Сhange this place of code
{% load static from staticfiles %}
Photo
And write like this
{% load staticfiles %}
And you can add css in static dir and include css in template
<link rel="stylesheet" href="{% static 'css/style.css' %}">
To answer to your question follow the steps
Static
Create static files :
We create the static files to link the html files with this 3 files :
1/ CSS files
2/ JS files
3/ IMAGES files
..
How to create the static files ?
1/ Go to the project files and create a folder name it static.
static / CSS-JS-Images
2/ Go To the settings file and search for static after the STATIC_URL.
add this Two line:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILESDIRS = [ os.path.join(BASE_DIR, 'here you type the direction of the static file') ]
Make sur that you're import the OS library
3/ finally you should collect static, to do that go on the terminal and add this code :
python manage.py collectstatic
here you find how to load static on the html file.
add this code on the top of the page :
{% load static %}
add this code To link CSS file with Html.
<link reel = 'stylesheet' href = " {% static 'dir of css file.css' %} "
May that help you.

Django CSS. I get the HTML page with no CSS

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.

Static files are not loaded in Django

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.

Django Static Setup

I've looked through countless answers and questions trying to find a single definitive guide or way to do this, but it seems that everyone has a different way. Can someone please just explain to me how to serve static files in templates?
Assuming I've just created a brand new project with Django 1.4, what all do I need to do to be able to render images? Where should I put the media and static folders?
Put your static files into <app>/static or add an absolute path to STATICFILES_DIRS
Configure your web server (you should not serve static files with Django) to serve files in STATIC_ROOT
Point STATIC_URL to the base URL the web server serves
Run ./manage.py collectstatic
Be sure to use RequestContext in your render calls and {{ STATIC_URL }} to prefix paths
Coffee and pat yourself on the back
A little bit more about running a web server in front of Django. Django is practically an application server. It has not been designed to be any good in serving static files. That is why it actively refuses to do that when DEBUG=False. Also, the Django development server should not be used for production. This means that there should be something in front of Django at all times. It may be a WSGI server such as gunicorn or a 'real' web server such as nginx or Apache.
If you are running a reverse proxy (such as nginx or Apache) you can bind /static to a path in the filesystem and the rest of the traffic to pass through to Django. That means your STATIC_URL can be a relative path. Otherwise you will need to use an absolute URL.
The created project should have a static folder. Put all resources (images, ...) in there.
Then, in your HTML template, you can reference STATIC_ROOT and add the resource path (relative to the static folder)
Here is the official documentation:
How to manage static files: https://docs.djangoproject.com/en/1.4/howto/static-files/
Static Files in general: https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/
If you are planning to to deploy in a production type setting then you should read the section here: https://docs.djangoproject.com/en/1.4/howto/static-files/#staticfiles-production
Generally you put our static and media folders outside of the django project app
Define your STATICFILES_DIRS, STATIC, and MEDIA path in the settings.
Create staticfiles folder beside your templates folder, urls.py, settings.py, etc...
You don't have to create media folder because it will automatically created when you upload images.
In your urlconf put this one:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
.............
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
In templates:
{% load static %}
<img src="{% static 'images.png' %}">
<img src="{{MEDIA_URL}}images.png">

Categories