How to access media file's URL from within template? - python

This question regards development server.
I have an audio file audio1.wav sitting in my MEDIA_ROOT/audio folder.
How can I attach such element to an <audio> tag in the template?
<audio src="?"></audio>
Do I need to construct an absolute URL for the file like http://127.0.0.1:8000/media/audio/audio1.wav (given MEDIA_URL is set to /media/)?
If so, how? Or perhaps there is a better way that will also cover for variable audio file name?

You will need to use get_media_prefix to get media url:
{% load static %}
<audio src="{% get_media_prefix %}audio/audio1.wav"></audio>

Related

Load Media Files in Django

I'm trying to create a home media server using Django. For this I want it to be in such a way that my media files are stored in an external USB. Now from my code when I try to load the video, it doesn't work. I even tried hard coding a path to see if it works. When I run through Django, It doesn't work but when I directly open the HTML in chrome It works perfectly.
Placeholder Template Code:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<video width="640" height="480" controls autoplay>
<source src="E:/Programming\Projects\Youtube Downloader\Ariana Grande - One Last Time (Official).mp4" type="video/mp4">
</video>
<p><b>Note:</b> The autoplay attribute will not work on some mobile devices.</p>
</body>
</html>
Actual Template:
{% extends 'MediaPlayer/layout.html' %}
{% block MainContent %}
{{ video_source}}
<video width="640" height="360">
<source src="E:/OneLastTime.mp4" type="video/mp4">
</video>
<p><b>Note:</b> The autoplay attribute will not work on some mobile devices.</p>
{% endblock %}
{% block PageScripts %}
{% endblock %}
View that calls the template:
def select_video_page(request, video_id):
file_path = FILE_SCANNER.files["video"][video_id]
context = {
"video_source": file_path,
"title": '.'.join(file_path.split("\\")[-1].split(".")[:-1])
}
return render(request, "MediaPlayer/selectvideopage.html", context)
Everything on the page works perfectly fine, Template loads and everything. Only issue i'm facing is with the video file. Almost all the solutions I have found requires storing the Media in a media directory under Django, But this would defeat the purpose of my project.
If you post your settings.py it will be helpful in determining your problem.
You are trying to serve static media from your Django project. You need to properly specify which directory you want to use as your media root, i.e. your USB drive. Additionally I don't see any non-trivial way to enable the django app to support hot-plugging of the USB drive, this may also lead to other problems if the media is disconnected.
This HTML indicates that you are not serving the files from the Media Server (unless you have defined your MEDIA_URL as E: in settings.py)
Even if you got this url to render a video, it would not work for any other network device unless the file is being served by django's media server given the filesystem path below.
<source src="E:/OneLastTime.mp4" type="video/mp4">
django static file serving guide
You will most likely need to use python's OS module to navigate to the directory on your usb drive and then declare this directory as your media root for django to serve files from it. There may be built in security features that prevent serving files from outside the root of the project.

Cannot call service in my index.html file; Django error

I am currently working on implementing multiple themes in my web application using bootswatch. The user can choose what css theme they would like to see on the web application by choosing from a pick-list.
I have written a service, kjTheme, to handle this. Ideally, when a user chooses a new theme (say, "Cyborg") in the front-end, my index file will use the line of code:
<link rel="stylesheet" type="text/css" href="" data-ng-href={{ $kjTheme }}"/>
To reference my service. My service then references the corresponding css file path (i.e. '/libs/bootswatch/cyborg/bootstrap.min.css').
However, I am running into a Template Syntax Error.
Exception Value: Could not parse the remainder: '$kjTheme' from '$kjTheme'
And the exception location points to my django\template\base.py
Any ideas as to what I'm doing wrong, or what I could check to get me on the right path?
Thank you!
Django and AngularJS both use the double brace syntax {{ variable }} you will need to escape the double braces at the Django template level so that Django does not try to render your tag
data-ng-href="{% templatetag openvariable %} $kjTheme {% templatetag closevariable %}"
You need to tell Django not to try to parse the Angular tags. Use {% verbatim %} to do that.

How to get absolute URL with domain and protocol in a Django template? [duplicate]

In Django, when I use:
{{ request.build_absolute_uri }}{% static "img/myimage.jpg" %}
It produces: 'http://myurl.com//static/img/myimage.jpg'. This produces an error.
How can I remove the double slashes?
The STATIC URL is:
STATIC_URL = '/static/'
But I don't think removing the first '/' would be a good idea.
The request object is available within your templates and you can easily access attributes such as request.scheme or request.META.HTTP_HOST to construct your base URL that you can prepend ahead of your static URL to get the full URL.
Final example would look something like this:
<img src="{{request.scheme}}://{{request.META.HTTP_HOST}}{% static 'img/myimage.jpg' %}">
The build_absolute_uri method builds an absolute uri for the current page. That means that if you're on e.g. 'http://myurl.com/login/', the resulted full url would be 'http://myurl.com/login//static/img/myimage.jpg'.
Instead, use request.get_host() (optionally together with request.scheme for the url scheme), or preferably, use the sites framework to set a template variable to the current site domain. The get_host() method has some issues regarding proxies.
The get_host() method will return the current domain without a path appended.
I just made a quick template tag for doing this. Create files /myapp/templatetags/__init__.py and /myapp/templatetags/my_tag_library.py, if you don't have them already, and add the following to my_tag_library.py:
from django import template
from django.templatetags import static
register = template.Library()
class FullStaticNode(static.StaticNode):
def url(self, context):
request = context['request']
return request.build_absolute_uri(super().url(context))
#register.tag('fullstatic')
def do_static(parser, token):
return FullStaticNode.handle_token(parser, token)
Then in your templates, just {% load my_tag_library %} and use e.g. {% fullstatic my_image.jpg %}.
In response to earlier comments wondering why someone would need to do this, my particular use case was that I wanted to put a link to a static file inside of an open graph protocol meta tag, and those links need to be absolute. In development the static files get served locally, but in production they get served remotely, so I couldn't just prepend the host to get the full url.
Is this worth an update (Django 2+)?
This helped me specifically because I was trying to put a query in the link, i.e. the myimage.jpg was actually pulling from the DB. I needed a way to put it in the src, which was to replace 'myimage.jpg' with {{ img_link_field_in_model }}.
<img src="{% get_static_prefix %}img/myimage.jpg">
will produce:
<img src="/static/img/myimage.jpg">
The example of the query is:
<img src="{% get_static_prefix %}img/{{img_link_from_model}}">
Use this for apps:
{{ request.build_absolute_uri|slice:":-1" }}{% static "img/myimage.jpg" %}
Use this generally:
{{ request.scheme }}://{{ request.META.HTTP_HOST }}{% static "img/myimage.jpg" %}
Not entirely sure what you're asking, but since the {% static .. %} is only adding /static/ to the front of your path you specify, you could just do that yourself:
{{ request.build_absolute_uri }}static/img/myimage.jpg
Not very modular, but then again most times you don't need direct access to the full url since it will just append it onto whatever url you're at if you use it as a src for some html object.
build_absolute_uri takes the location as an argument which handles the double slash problem.
Unfortunately you cannot pass arguments via the django template language.
You will need to build a custom template tag or filter which accepts an argument to the build_absolute_uri function.
One of the many reasons I prefer Jinja as I can just do this:
{{ request.build_absolute_uri(static('img/foo.png')) }}

Django static templatetag not displaying SVG

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.

showing image in templates using django

I am new to django. My project folder contain media folder. It contain some images.
How can I display this images in template of another app?
Path : mysite/media/blog/templates/blog/details.html
details.html
{{<img src="media/image_2.jpg">}}
But it does not display anything..
You should set-up the STATIC folder and to configure the media files.
The full reference: https://docs.djangoproject.com/en/dev/howto/static-files/ and also
https://docs.djangoproject.com/en/1.4/howto/static-files/.
However you should use something like this (once you configured properly the STATIC files) :
<img src="{% static "media/myexample.jpg" %}"/>
Edit:
Before using static tag, You must load specific tags incluing on top of template code: {% load staticfiles %} : Referring to static files in templates

Categories