Django serving dynamic Files - python

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}}" />

Related

Need solution to display media files in template when debug == false

My Django project is displaying media in templates if debug == True no problem at all but the problem arises when I set debug to False
Django fails to load them if debug == False( There are some solutions out there but I am not able to wrap my head around them as
I am new to Django ). Can someone please tell me what is the best and easiest way to solve this issue?
Note: I want to host my website on my local wifi (not on pythonanywhere or any other web hosting service)
Thanks in advance.
For me below method worked:
In urls.py I added this line:
from django.views.static import serve
add those two urls in urlpatterns:
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
and both static and media files were accesible when DEBUG=FALSE.
Hope it helps
For more info. , Take a look at Why does DEBUG=False setting make my django Static Files Access fail?

(Django) How to apply css?

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).

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">

Why can't Django find my admin media files once I leave the built-in runserver?

When I was using the built-in simple server, everything is OK, the admin interface is beautiful:
python manage.py runserver
However, when I try to serve my application using a wsgi server with django.core.handlers.wsgi.WSGIHandler, Django seems to forget where the admin media files is, and the admin page is not styled at all:
gunicorn_django
How did this happen?
When I look into the source code of Django, I find out the reason.
Somewhere in the django.core.management.commands.runserver module, a WSGIHandler object is
wrapped inside an AdminMediaHandler.
According to the document, AdminMediaHandler is a
WSGI middleware that intercepts calls
to the admin media directory, as
defined by the ADMIN_MEDIA_PREFIX setting, and serves those images.
Use this ONLY LOCALLY, for development! This hasn't been tested
for
security and is not super efficient.
And that's why the admin media files can only be found automatically when I was using the test server.
Now I just go ahead and set up the admin media url mapping manually :)
Django by default doesn't serve the media files since it usually is better to serve these static files on another server (for performance etc.). So, when deploying your application you have to make sure you setup another server (or virtual server) which serves the media (including the admin media). You can find the admin media in django/contrib/admin/media. You should setup your MEDIA_URL and ADMIN_MEDIA_URL so that they point to the media files. See also http://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files.
I've run into this problem too (because I do some development against gunicorn), and here's how to remove the admin-media magic and serve admin media like any other media through urls.py:
import os
import django
...
admin_media_url = settings.ADMIN_MEDIA_PREFIX.lstrip('/') + '(?P<path>.*)$'
admin_media_path = os.path.join(django.__path__[0], 'contrib', 'admin', 'media')
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^' + admin_media_url , 'django.views.static.serve', {
'document_root': admin_media_path,
}, name='admin-media'),
...
)
Also: http://djangosnippets.org/snippets/2547/
And, of course, #include <production_disclaimer.h>.

Where to put a Django template's dependent files?

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

Categories