My Django templates use a lot of related stuff: images, style sheets, etc.
Where should I put these file, or how should I refer to them in the template itself?
For now I'm using the development server.
I know it's a really common thing, but I can't really figure it out.
I put them inside a folder named static, which is in the web project's top level folder.
Example:
/static/img/
/static/js/
/static/css/
/templates/
urls.py
settings.py
I then have the following rule in my urls.py file:
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
My settings.py contains:
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'static').replace('\\', '/')
ADMIN_MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'static/admin').replace('\\', '/')
Maybe you can read the doc http://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files
We put ours under /media. Everything that is specifically tied to the layout of the sites is further separated. Of course none of this static content is served by Django on the production site. They often aren't even on the same physical server.
/media
/images - this is for content-specific images
/video - these next 2 are normally symlinks to a /big_content folder ...
/audio - so that they aren't included in our mercurial repository.
/layout - everything that is tied to the basic templates.
/css
/js
/images
Related
I want to apply CSS on my Django project.
CSS path in my index.html is right but it doesn't work well.
My index.html page show up well in my site,
--app_index
----index.html
----bootstrap
-------css
-----------abc.css
-----------abc2.css
So, must I modify the URL.py file too?
You need to configure static files in your Django app. The following links should help guide you in the right direction:
http://www.tangowithdjango.com/book/chapters/templates_static.html
https://docs.djangoproject.com/en/1.7/howto/static-files/
You will set up your index.html for example in a template directory that can access your static files (e.g. CSS, javascript, static images, etc.) that are located in your static directory.
In response to your question concerning modification of urls.py, the answer is yes. As you will see in the links on configuring static files within your project, you have to add some code to your urls.py. An example of this code might look like this:
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}),
url(r'^__debug__/', include(debug_toolbar.urls))
)
During development Django serves your static files hence the above code, but during production your static files are served via your configured server (e.g. Apache, nginx).
Now, I have a Django web site which has two projects. One is root project and another is a app.
The directory structure is below:
--root project
--static
--templates
--index.html
--app
--static
--templates
--index.html
The relative settings in setting.py is below:
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__).decode('utf-8')).replace('\\', '/')
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, "static"),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
And, when I want to specify a path to "/app/static/templates/index.html", I always get index.html in root.If I change the turn in STATICFILES_FINDERS, I will face the same problem when I want to get index.html in root.
How can I accurately get one of them?
Your directory structure seems strange...
First thing, in case the index.html in the app directory is supposed to be a Django-template, it shouldn't be under the static directory.
Also, you mentioned that you used the path /app/static/templates/index.html, which actually shouldn't work at all.
Usually in Django, the /static/ path will be used to access static resources from all apps' static directories, as well as all directories specified in STATICFILES_DIRS, as if all the content from all those directories is "merged" into one /static/ directory!
So, in your example, the path /static/templates/index.html indeed refers to both the index.html from the root project directory, as well as the index.html from the app-specific static directory, which is why the actual file you get will depend on the order of static files finders specified.
The recommended layout to avoid such collisions would be:
-project root
-static
-global static resources accessible via /static/...
-app
-static
-app
-app-specific static resources accessible via /static/app/...
This is also appropriate for app-template directories:
-app1
-templates
-app1
-index.html (referred from Django view as 'app1/index.html')
-app2
-templates
-app2
-index.html (referred from Django view as 'app2/index.html')
Edit to add info on shared templates:
If you're trying to have a "base-template" that is extended by other apps, I would recommend using the "common-app" approach.
You simply create a new app (named e.g. "common", although you can name it however you want), that contains common templates (and other logic, if you'd like), and have the app-specific templates extend it.
The layout would be:
-app1
-templates
-app1
-index.html
-common
-templates
-common
-base.html
And in index.html you'll have {% extends "common/base.html" %} at the top of the file (read the Django docs on template inheritance if you're unfamiliar with it).
Of course, the common app must be enabled in the Django settings for this to work.
I have a problem about serving admin uploaded files in my templates.
I set:
MEDIA_URL='/media/'
MEDIA_ROOT = 'assets/'
and my models are like:
mainPhoto = models.ImageField(upload_to="articles/")
When in my templates, I try:
<img src="{{MEDIA_URL}}{{article.mainPhoto}}" />
The image doesn't show up on the website.
I found one deprecated solution with the django .serve(), but I hope to avoid using it.
I was looking everywhere and didn't find any answer, so I hope someone here will be able to help me.
There are two parts to make this work. First is the Django configuration. There are really two settings for this which you have already mentioned - MEDIA_URL and MEDIA_ROOT. As already noted in the comments the MEDIA_ROOT has to be an absolute path. For example:
MEDIA_ROOT = `/abs/path/to/project/media/`
Second part is actually serving the files. If you are in production, you NEVER want to serve your static or media files through Django so you should configure Apache or nginx or whatever server system you are using to serve the files instead of Django. If you are on the other hand still developing the app, there is a simple way to make Django serve media files. The idea is to modify your urls.py and use the Django's static files server to serve media files as well:
# urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# other patterns
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
More about this approach at Django docs.
Also FYI, you probably should not use {{MEDIA_URL}}{{article.mainPhoto}} to get the url of an image. This approach will break for example if you will no longer use file system storage for static files and will switch to something different like Amazon S3. It is always a good idea for the storage backend to figure out the url:
<img src="{{article.mainPhoto.url}}" />
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">
This should be super simple, but somehow its has had me stuck all morning. I'm developing locally, using the django debug server, and with this filestructure:
/project/ (django project)
/static/ (static files)
In the settings.py MEDIA_ROOT and MEDIA_URL are both set to '/static/' and I'm using this in my urls.py
url(r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': '../static'}),
In my templates, the files that need to be server from the static directory are configured as such:
<link rel="stylesheet" href="{{ STATIC_URL }}css/style.css">
That all works as it should - the javascript/css/images are all served properly from the hompage. However, when I go to a subdirectory, such as http://127.0.0.1:8000/news/ then all the links are broken.
I've tried using a variety of the os.import options to get it to do the relative links properly, but havent had any luck. Is there a way that I could force it to be relative to the base url, or perhaps hardcode it to my filesystem?
Any help would be amazing!
In this line in your urls.py file, the '../static' should be changed to an absolute directory. Try changing it and see what happens.
Your file:
url(r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': '../static'}),
Should look more like:
url(r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/full/path/to/static'}),
To give you an example, mine is set up a little differently, but I still use a full path.
Here's how mine is setup:
in settings.py
STATIC_DOC_ROOT = '/Users/kylewpppd/Projects/Django/kl2011/assets/'
and in urls.py:
(r'^assets/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DOC_ROOT, 'show_indexes':True}),
I'm serving my static files from 'localhost:8000/assets/'.
I just had the same problem, and I solved it by removing first slash from STATIC_URL='/static/' and making it STATIC_URL = 'static/' just like philipbe wrote above.
Wierd thing is that '/media/' works fine for MEDIA_URL at the same time (while 'media/' breaks layout).
Anyway - just change STATIC_URL to be equal to 'static/' with no leading slash, and you'll solve it.
How do your links break when you go to a subdirectory? Can you explain that further please.
Does django 1.3 support some kind of strange relative url routing for static media?
If it can be served from the homepage but not others, doesn't that sound exactly like your STATIC_URL is a relative location?
What is your STATIC_URL? It should be absolute and start with a slash.