Generating audio files in a Django project template - python

I am attempting to create a pretty simple website using Django that will have a number of audio files stored in it and available for streaming and downloading. I know that there are other ways to do this, like using AWS, but I wanted to figure this way out first. I'll include my template here but wanted to note that it is currently messy because I have been experimenting with different structures to figure this problem out.
{% for song in concert.song_set.all %}
<li>{{ song.song_title }}</li>
<li>{{ song.song_location }}</li>
<!-- Working -->
<audio
class = "audioPlayer uniqueShowAP"
controls <--controlsList="nodownload"
src="{% static 'shows/audio/redRocks2019/01 Yi.mp3' %}">
Your browser does not support the
<code>audio</code> element.
</audio>
<!-- Not Working...yet -->
<audio
class = "audioPlayer uniqueShowAP"
controls <--controlsList="nodownload"
src="/shows/static/shows/{{ song.song_location }}">
Your browser does not support the
<code>audio</code> element.
</audio>
{% endfor %}
What I want to happen is for every concert that I save it will go through the songs saved under that concert and add them to under the name of the song. I have each song's relative location saved in the data base so that I should be able to just call upon it's location.
I've tested this out by calling {{ song.song_location }} which correctly displays each song's location.
I also tried using src="{% static 'shows/audio/redRocks2019/01 Yi.mp3' %}" just to make sure that the element is at least set up correctly and that works too.
How do I format the src="" in the element to point it to the correct audio files? I can include my views and models or whatever additional information you might need to help me figure this out. I've been at this for a while now and just need someone to point me in the right direction.

I think you should look into using a FileField. You can have a Song model, with a song_file = FileField(upload_to='song_files/') field. Then, the files can be saved and accessed more easily when looping through model instances:
<audio src='{{ song.song_file.url }}' controls></audio>
These files will be stored locally per your media settings. You can easily transition to using a storage solution like S3 for your media files, as you mentioned. It works incredibly smoothly with Django, so don't be scared.
Static files should be for things like css, js, and images that aren't going to change, like a favicon perhaps. I guess it could be used for a static song, hypothetically. But thinking about using static files this way above in conjunction with a model instance is a bit contrived and confusing, I think.

Related

Sorl-Thumbnail not appearing

Firstly i'm very much a beginner and learning Django, but I just cannot get Sorl-Thumbnail to work in the Gallery aspects of a photography site I am developing.
The site is in development and DEBUG = True, all installs went well including dependencies as far as I can see. 'sorl.thumbnail', is added to apps and migrations have gone through.
I am using is to generate thumbnail within a template for loop to generate my galleries. But I get broken thumbnails for each image objects. On inspecting i get a tag img tag
<img src="/media/cache/5c/58/5c58ba75425e372e94b739e292690b85.jpg">
All other images work in Admin, and on the rest of the site. I've checked MEDIA_URL but this seems ok. I cannot see a cache folder within my media folder though, does sorl generate one?
I've changed my model so it is using the Sorl-Thumnail imagefield, but this didn'd achieve anything, I have THUMBNAIL_DEBUG = True in setting but this is not giving me anything in terminal.
{% for img in album.images %}
{% thumbnail img "100x100" crop="center" as im %}
<img src="{{ im.url }}">
{% empty %}
Well, I didin't manage to solve this. I 'think' it maybe a permissions problem (I'm using Windows) but I could never get any errors back from sorl-thumbnail so little info to go on. I worked on all the other solutions on SO but I could never get it to create the Cache folder.
I removed the module and used Imagekit in the end which worked like a charm. I'm just annoyed I never got to the bottom of my problem with Sorl.

detect image errors django template

I pull in image links from several sources so I have a mix images that render and then have problems rendering.
I have many images that return with http error 400, 403 etc.
Am I able to detect this in the django template so that I can render something more suitable than a broken image?
Something like:
{% if ia.image.url %}
<img src="{{media_url}}{{ia.image.url}}" alt="#" class="trimimg1" />
{% else %}
<img src="{% static 'common/app/images/news-default.jpg' %}" alt="#" class="trimimg1" />
{% endif %}
You are able to detect broken links in the django template or also before in the view. However, depending on the type of project you are doing, I would not recommend this - at least not without caching.
Let's talk about the theory first and then about a possible alternative solution:
If you only are using images that you are hosting yourself, serving the images to your clients should be no problem as long as the files on your server exist. You can easily check that by retrieving the path of the image and checking if the file exists (provided, that you may access the file and did not separate completely the media server, then you have to handle this as if it is external hosting).
If I read your question carefully, you seem to link to images hosted on external servers though. It is possible to handle a few but probably not all problems with those images on the server side. Either you do this while storing the image URL already, or you do a periodical check in the background. If you really want to check every time you are sending the image URL to the user, you might create a heavy load on the server just for checking. In this case, I recommend to rely heavily on caching and to cache the return value of the method for checking the availability of the URL for a certain time.
That being said, you could do the following in your template:
In theory, you could create your own custom filter "urlexists" (See https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/ ). This filter would retrieve the URL you want to check. It would try to retrieve the file from the remote server (Download just the headers, see https://stackoverflow.com/a/16778473/1331407 on how to do that) and return True, if the URL exists and False otherwise.
Usage:
{% if ia.image.url|urlexists %}
<img src="{{media_url}}{{ia.image.url}}" alt="#" class="trimimg1" />
{% else %}
<img src="{% static 'common/app/images/news-default.jpg' %}" alt="#" class="trimimg1" />
{% endif %}
As I said, it is a solution but I do not recommend this.
Alternative solution
I would rather recommend to handle the HTTP error on the client side using JavaScript. That script can be as easy as an and a JavaScript function that then replaces the image src with a placeholder image that you provide.
Examples on how to do that are provided here: Detecting an image 404 in javascript
You could even do one better: If you want to know about the inaccessible image, you could modify the URL of the placeholder image to a view that retrieves the image URL and logs it somewhere in your database so that you can remove the URL from your image database later. The view would always just return the placeholder image.
Why do I recommend handling this error on the client side?
Simple answer: Server load and access rights. Checking all URLs constantly will create a huge server load and traffic, both of which you might not want to handle all the time. In addition, your server might not be allowed to access certain images that you would filter out - or vice versa. Some servers allow you only to access their images after you loaded a page containing those images beforehand (I learned that trying to scrape movie posters from websites for my personal BluRay library index). An image that your server might have scraped from somewhere and that you are able to access might thus not be accessible for your clients webbrowser. Thus he might still see broken images. If you check the availability on your clients browser, he will never see the broken image, since his or her browser is always replacing those with a placeholder. If you include my suggestion above, you would even crowdsource image availability checking, reducing server load on your and foreign servers.

In PyCharm: "Unused local variable..." using multiple JavaScript template files

I'm using PyCharm for my Django project and In my file product_header_js.html:
<script>
{% include 'global_variables.js' %}
{% include 'update_scene_function.js' %}
...
// I may use variables in here or in update_scene_function.js
</script>
I would like to use variables in global_variables.js in my update_scene_function.js file and product_header_js.html file. PyCharm lets me do this, but gives me the error Unused local variable... in global_variables.js and all my variables are greyed out because PyCharm doesn't think they are being used. Is there anyway to fix PyCharm?
So what generated this question was me trying to modularize my JavaScript code, but it looks like I might have to just deal with the PyCharm warnings. Even when I add JavaScript as a template file type, PyCharm's JavaScript interpreter still gives me warnings (not Django template tag warnings) when I do something like this:
{% if something %}
var my_var = "a";
{% else %}
var my_var = "b";
{% endif %}
It'll say Duplicate declaration. And when I reference a variable not in the current template file or when I don't use a variable declared in the current template, PyCharm complains.
So in summary, you can do this, but PyCharm will complain and the CTRL + clicking to jump to declarations doesn't work.
One of my follow-up questions would be, if you can tolerate the PyCharm warnings, is including JavaScript files better performing than multiple external JavaScript files (). I would think including would perform better most of the time (except if most of your traffic is returning visitors where you could use external JavaScript files and leverage caching).

Python / Django - Organizing Stylesheets and Scripts

I am looking for a simple way to organize stylesheets and scripts in Django. I am relatively new to the framework and language of python. I'm coming from a PHP background.
In the world of PHP / Zend there are functions that are implemented with the view/layout object. By including a single line inside your head tag for scripts and for stylsheets you can easily add a stylesheet/script in the view -> method level. I have read the Django Form Media Documentation, but this only pertains to forms needing specific styles and scripts.
Any direction?
Look at the django.contrib.admin application.
Parallel the way the admin site works.
Create a media directory.
Create media/img, media/jss, media/css, media/whatever directories
In each of these, you'll have your app's specific stuff. media/img/app1, media/jss/app1 so that each of your Django apps can have specific media without conflict or problems.
Be sure that your settings have the MEDIA_ROOT set. You'll want to read about this in the Django docs. You'll also have to set your MEDIA_URL for deployment. And you'll have to figure out how to make your webserver (i.e., Apache) serve this media.
Django should not be serving static files like .js libraries or .css files or any images. It's a waste of time. Apache can serve this just fine. For testing purposes, however, you can enable a simple file server capability in your Django site.
Finally. And most importantly.
Be sure that your page template actually references the various files you want to include on your page {{MEDIA_URL}}css/site.css, and {{MEDIA_URL}}js/app1/something.js.
Be aware that as of django 1.3, the old staticfiles app has become part of django.contrib.
The main thing to know is that you can stick your static media in a static/ subdir in any app that is in your settings.INSTALLED_APPS, and that file will be automatically collected by the collectstatic management command.
Rather than re-hash, I'll just point you at the docmentation: Django: the staticfiles app.
You might also want to consider looking for something that will process your text-based static files (css and javascript), which can easily be combined, minified and versioned. I'm about to look hard into this, so no links yet.
I like to have style-related images close to my stylesheets, and a different path for user uploaded content like profile pictures, photos, videos...
So I end-up with something like this:
/media
/style
base.css
img/
logo.gif
button.gif
/js
home.js
/profile
user_profile_image.gif
This way, image references inside css can be always relative like:
background: url(img/background.gif)
Also, there are some apps for handling media, css / js compression, sprites, etc.
It seems like you might actually looking for a way to conditionally include a stylesheet based on the current page. This can be done using template tags.
In your base.html file you would create a section to add stylesheets.
{% block addl_styles %}{% endblock %}
Then in the page you want to load the styles you would use the same block along with block.super to append your script to any other scripts called by your application.
So in your form's template you would use code like the following:
{% block addl_styles %}
{{ block.super }}
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}your_css_folder/example.css" />
{% endblock %}
Please note that you can programmatically add the base dir using {{ MEDIA_URL }} and arrive at your folder in a safe manner.

What specific issue try zope folks to solve with TAL, TALES & METAL

TAL, TALES and METAL are all three the zope templating language. The thing that I don't understand is why so much troubles. I don't understand the spirit of ZTL, any tips ?
one more question : is there a standalone library that try to achieve the same thing that ZTL but outside the Zope ecosystem ?
The core idea of tal/tales is to have proper valid (x)html. All the template functionality is in attributes or namespaced elements. HTML editors should work just fine with these templates. Let's give an example. First tal/tales:
<ul>
<li tal:repeat="customer customers">
<a href=""
tal:attributes="href customer.url"
tal:content="customer.name>
Sample customer name
</a>
</li>
</ul>
And in Django's template language, just as an example:
<ul>
{% for customer in customers %}
<li>
<a href="{{ customer.url }}">
{{ customer.name }}
</a>
</li>
{% endfor %}
</ul>
Which one's better? Open question. One plays nice with your html editor, the other makes the non-html statements clearer. Anyway, making it proper html is the main idea behind tal/tales!
Your last question: http://zpt.sourceforge.net/
Since the other question isn't that specific, I'm not sure there's a definitive answer to this, unless one of the original developers answers.
Zope Page Templates is the templating system making use of TAL/TALES/METAL, and the specific issue it tries to solve is the same as with many other templating systems: produce valid HTML. In the case of ZPT it is possible to create also any flavour of XML. At the time of its creation, it had some outstanding properties:
the templates itself could be used in designing tools like Dr*beep*mw*beep*ver or Fr*beeb*ntp*beep*ge without modification
the nested structure of XML/XHTML was ensured (invalid structured XML wouldn't work)
the templates themselves could be nested, mixed and matched
pure python implementation (rather clean code) and embedded python expressions
in the meantime the web has caught up and there are many alternatives available

Categories

Resources