I am trying to find the most efficient way of displaying an image using django's template context loader. I have a static dir within my app which contains the image 'victoryDance.gif' and an empty static root dir at the project level (with settings.py). assuming the paths within my urls.py and settings.py files are correct. what is the best view?
from django.shortcuts import HttpResponse
from django.conf import settings
from django.template import RequestContext, Template, Context
def image1(request): # good because only the required context is rendered
html = Template('<img src="{{ STATIC_URL }}victoryDance.gif" alt="Hi!" />')
ctx = { 'STATIC_URL':settings.STATIC_URL}
return HttpResponse(html.render(Context(ctx)))
def image2(request): # good because you don't have to explicitly define STATIC_URL
html = Template('<img src="{{ STATIC_URL }}victoryDance.gif" alt="Hi!" />')
return HttpResponse(html.render(RequestContext(request)))
def image3(request): # This allows you to load STATIC_URL selectively from the template end
html = Template('{% load static %}<img src="{% static "victoryDance.gif" %}" />')
return HttpResponse(html.render(Context(request)))
def image4(request): # same pros as image3
html = Template('{% load static %} <img src="{% get_static_prefix %}victoryDance.gif" %}" />')
return HttpResponse(html.render(Context(request)))
def image5(request):
html = Template('{% load static %} {% get_static_prefix as STATIC_PREFIX %} <img src="{{ STATIC_PREFIX }}victoryDance.gif" alt="Hi!" />')
return HttpResponse(html.render(Context(request)))
thanks for answers These views all work!
If you need to render an image read a bit here http://www.djangobook.com/en/1.0/chapter11/ and use your version of the following code:
For django version <= 1.5:
from django.http import HttpResponse
def my_image(request):
image_data = open("/path/to/my/image.png", "rb").read()
return HttpResponse(image_data, mimetype="image/png")
For django 1.5+ mimetype was replaced by content_type(so happy I'm not working with django anymore):
from django.http import HttpResponse
def my_image(request):
image_data = open("/path/to/my/image.png", "rb").read()
return HttpResponse(image_data, content_type="image/png")
Also there's a better way of doing things!
Else, if you need a efficient template engine use Jinja2
Else, if you are using Django's templating system, from my knowledge you don't need to define STATIC_URL as it is served to your templates by the "static" context preprocessor:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.static',
'django.core.context_processors.media',
'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages',
)
In your last example (image5) you should use {{ STATIC_PREFIX }} instead of {% STATIC_PREFIX %}
STATIC_PREFIX is variable, not a tag
To avoid defining STATIC_URL explicitly, you can use a RequestContext when rendering your template. Just make sure django.core.context_processors.static is in your TEMPLATE_CONTEXT_PROCESSORS setting.
from django.template import RequestContext
...
return HttpResponse(html.render(RequestContext(request, ctx)))
Alternatively, you could use the static template tag.
html = Template('<img src="{% static "victoryDance.gif" %} alt="Hi!" />')
A third option is the get_static_prefix template tag.
Related
I am using Multisite to administer several websites and a custom admin on a single build of Wagtail. Currently, I have my static folder set like this:
settings.py:
INSTALLED_APPS = [
'websites.sua_umn_edu',
'admin_sua_umn_edu',
...
]
STATIC_URL = '/static/'
Is there some way to set the STATIC_URL dynamically, so each app looks for a static directory within its own folder?
Maybe a template tag that creates a path based on the request.site fits your needs? I created a template tag for a per site stylesheet:
#register.inclusion_tag('website/tags/stylesheet.html', takes_context=True)
def stylesheet(context):
slug = slugify(context['request'].site)
return {
'path': '/css/{}/main.css'.format(slug)
}
website/tags/stylesheet.html
{% load static %}
<link rel="stylesheet" href="{% static path %}">
This template tag can be used in your base.html
{% stylesheet %}
Maybe stylesheets is too limited for your websites but this concept can be generalised. Here is pseudo code for a {% site_static '...' %} template tag. It looks up the current site and calls the normal static template tag.
from django.templatetags.static import do_static
#register.tag('site_static', takes_context=True)
def site_static(context, parser, token)
site_slug = slugify(context['request'].site)
token = '{}/{}'.format(site_slug, token)
return do_static(parser, token)
I am not able to play video on my Django website. I think something is wrong in my views.py render function
videoplay.html:
{% block contents %}
<video name='demo' controls autoplay width='50%' height='40%'>
<source src="{{STATIC_URL}}sample1.mp4" type="video/mp4"></source>
</video>
{% endblock %}
Included this in settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')`
Views.py is:
from django.shortcuts import render, redirect
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.views.generic.base import TemplateView
from uploads.core.models import Document
from uploads.core.forms import DocumentForm
def index(request):
return render(request, "core/videoplay.html")`
I am getting a play button and streaming line on my website
The STATIC_URL is where your static files are located such as CSS, Template Images, Javascript etc. There is a special Template Tag for Static Files in Django called {% static %}.
To generate the full url to where the static files are located, you use the template tag like this:
{% load static %}
<video src="{% static "/videos/demo.mp4" %}">
The MEDIA_URL is where your media files are located. Media files are uploaded files that change during the applications lifetime. They are not necessarily there at deployment but can be uploaded at any time by users or admins on the website.
Media files are set as fields on the model like this:
class DemoVideo(models.Model):
video = models.FileField(upload_to="videos")
They are accessed like this demovideo.video.url so in your template it would be src="{{demovideo.video.url}}.
Check if your file is a media or static file, and access it in the template in the correct way described above.
I want to generate an image with a static url in a view, then render it in a template. I use mark_safe so that the HTML won't be escaped. However, it still doesn't render the image. How do I generate the image tag in Python?
from django.shortcuts import render
from django.utils.safestring import mark_safe
def check(request):
html = mark_safe('<img src="{% static "brand.png" %}" />')
return render(request, "check.html", {"image": html})
Rendering it in a template:
{{ image }}
renders the img tag without generating the url:
<img src="{% static "brand.png" %} />
You've marked the string, containing a template directive, as safe. However, templates are rendered in one pass. When you render that string, that's it, it doesn't go through and then render any directives that were in rendered strings. You need to generate the static url without using template directives.
from django.contrib.staticfiles.templatetags.staticfiles import static
url = static('images/deal/deal-brand.png')
img = mark_safe('<img src="{url}">'.format(url=url))
Before I start please pardon my english, totally newbie in HTML and this is the very first django app I'm creating.
So let's say I want to view static images based on the input in the forms for testing purpose, so if I type in the form goat.jpg it will display goat.jpg
this is my html
<!DOCTYPE html>
{% load static %}
<html>
<head>
<title>test</title>
</head>
<body>
<center><img src="{% static "{{staticpath}}" %}" alt="gif" align="middle"/></center>
{{boldmessage}}
and this is my views
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
def generate(request):
context = RequestContext(request)
if request.GET:
path = request.GET.get('path','')
context_dict = {'staticpath':path}
return render_to_response("generated/generated.html", context_dict, context)
path is already a string, but if I remove the staticpath double quote django will raise an exception. So how do I exactly put the path's string in the html image source so it will display the static images correctly? thanks!
Calling {% static 'some/path/' %} will call the Django static file finders. If the image you are looking for is in a directory and you only pass the file name to {% static 'some/path' %} it will not find the file.
Read about the {{ STATIC_URL }} tag as solution that will avoid nesting tags. If your files are all stored in the root folder of your staticfiles directory (set by the STATIC_ROOT setting in settings.py) then this will work-
<img src="{{ STATIC_URL }}{{ staticpath }}"/>
However, it would probably be best to implement a function called by your view that SEARCHES your STATIC_ROOT folder, and all child folders, to find the full relative ( to STATIC_ROOT ) path for the file and returns it. The approach is convoluted but would work.
So far I made it to the part where a user uploads an image but how can I use those images which are located in my media folder? Here is what I tried :
my view:
#I even tried to import MEDIA_ROOT to use it in my template...
#from settings import MEDIA_ROOT
def home(request):
latest_images = Image.objects.all().order_by('-pub_date')
return render_to_response('home.html',
#{'latest_images':latest_images, 'media_root':MEDIA_ROOT},
{'latest_images':latest_images,},
context_instance=RequestContext(request)
)
my model:
class Image(models.Model):
image = models.ImageField(upload_to='imgupload')
title = models.CharField(max_length=250)
owner = models.ForeignKey(User)
pub_date = models.DateTimeField(auto_now=True)
my template:
{% for image in latest_images %}
<img src="{{ MEDIA_ROOT }}{{ image.image }}" width="100px" height="100px" />
{% endfor %}
and my settings.py MEDIA_ROOT and URL:
MEDIA_ROOT = '/home/tony/Documents/photocomp/photocomp/apps/uploading/media/'
MEDIA_URL = '/media/'
So again here is what I am trying to do: Use those images in my templates!
If you use the url attribute, MEDIA_URL is automatically appended. Use name if you want the path without MEDIA_URL. So all you need to do is:
<img src="{{ some_object.image_field.url }}">
On development machine, you need to tell the devserver to serve uploaded files
# in urls.py
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
{# in template, use sorl-thumbnail if your want to resize images #}
{% with image.image as img %}
<img src="{{ img.url }}" width="{{ img.width }}" height="{{ img.height }}" />
{% endwith %}
# furthermore, the view code could be simplified as
from django.shortcuts import render
def home(request):
latest_images = Image.objects.order_by('-pub_date')
return render(request, 'home.html', {'latest_images':latest_images})
On production environment using normal filesystem storage, ensure the webserver has permission to write to MEDIA_ROOT. Also configure the webserver to read /media/filename from correct path.
ImageField() has an url attribute so try:
<img src="{{ MEDIA_URL }}{{ image.image.url }}" />
You could also add a method to your model like this to skip the MEDIA_ROOT part:
from django.conf import settings
class Image(...):
...
def get_absolute_url(self):
return settings.MEDIA_URL+"%s" % self.image.url
Also I'd use upload_to like this for sanity:
models.ImageField(upload_to="appname/classname/fieldname")
Try these settings:
import socket
PROJECT_ROOT = path.dirname(path.abspath(__file__))
# Dynamic content is saved to here
MEDIA_ROOT = path.join(PROJECT_ROOT,'media')
if ".example.com" in socket.gethostname():
MEDIA_URL = 'http://www.example.com/media/'
else:
MEDIA_URL = '/media/'
# Static content is saved to here
STATIC_ROOT = path.join(PROJECT_ROOT,'static-root') # this folder is used to collect static files in production. not used in development
STATIC_URL = "/static/"
STATICFILES_DIRS = (
('', path.join(PROJECT_ROOT,'static')), #store site-specific media here.
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
For Django version 2.2., try the following:
#You need to add the following into your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
Your URL mapping
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #add this
# And then use this in your html file to access the uploaded image
<img src="{{ object.image_field.url }}">
You have to make the folder containing the uploaded images "web accessible", i.e. either use Django to serve static files from the folder or use a dedicated web server for that.
Inside your template code, you have to use proper MEDIA_URL values.