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.
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))
I'm trying to use django's static templatetag to display an SVG, but it doesn't seem to recognize the SVG as a valid image url. This is what I currently have:
settings.py
import mimetypes
mimetypes.add_type("images/svg+xml", ".svg", True)
landing.html
{% load staticfiles %}
<img src="{% static 'images/right-arrow.svg' %}" />
At least in my view.py, it recognizes the SVG mimetype:
views.py
print(mimetypes.guess_type(static('images/right-arrow.svg')))
# returns ('images/svg+xml', None)
The SVG does display in a non-django page, and it will download the SVG if I try to open the SVG path in a new browser tab.
I'm currently using python 3.4 and django 1.8.4.
I found the issue. In settings.py, it should be mimetypes.add_type('image/svg+xml', '.svg', True). image should be singular.
I faced a similar issue.I would recommend you to use :
src="{{ STATIC_URL }} images/right-arrow.svg" instead of src="{% static 'images/right-arrow.svg' %}"
svg format might not always identify django's method of obtaining staticfile contents.Hope this helps :)
Add this in your settings.py file.
import mimetypes
mimetypes.add_type("image/svg+xml", ".svg", True)
mimetypes.add_type("image/svg+xml", ".svgz", True)
In your cases you have added images in add_type which should be singular (image).
You are loading staticfiles and using static?
This is wrong.
Try changing {% load staticfiles %} <img src="{% static 'images/right-arrow.svg' %}" /> to
{% load static %} <img src="{% static 'images/right-arrow.svg' %}" /> and you also need to consider which app you should find your static files.
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.