Displaying Filepaths Correctly in Flask/Jinja2 - flask

I have a setup in a flask app where I can use a form to upload a file into the static/img directory for my application, and the metadata is stored in a record in a database.
When someone makes a request to the appropriate page, I want to read the file from the server using the filepath saved in the database.
Here's an example of the record when it's pulled from the database:
(3, 'My Info', 'My Description', 'www.url.com', 'static\\img\\aws_nameservers.PNG')
What I'd like to do is combine the last item in the above record with the url_for function to render the image stored at that location.
What I have right now is a set method that gets the last part of the file path:
{% set filepath = workshop_info[4][7:] %}
This returns img\\aws_nameservers.PNG
Then inside an img tag I have the following:
<img src="{{ url_for('static', filename=filepath) }}">
Which gives me the following result:
<img src="/static/img%5Caws_nameservers.PNG">
It seems like a simple thing, but I can't figure out how to render the string correctly inside the jinja2 template.
Thank you.
If there is a better approach than what I'm attempting, I'm happy to get corrected.

You should use the forward slash (/) instead of backslash (\) at the file path. You can replace them either in the Python code or in the template using a filter, e.g.:
{% set filepath = "img\\aws_nameservers.PNG" | replace("\\", "/") %}
{{ url_for('static', filename=filepath) }}
# Outputs: /static/img/aws_nameservers.PNG
You can also use the pathlib module to convert between the Windows and Unix style paths.

Related

Django - pass file path/URL from HTML to view in order to change the source of my video stream

I am fairly new to the Django and HTML world and and would like to be able to select a video file and then play it in an edited version (AI classification and some OpenCV editing).
At the moment, playing of a local file works in that way that the file path of my dummy video file is fixed in my script where I load the VideoStream.
However, I would like to be able to specify via HTML input which file to load.
I have the problem that I do not know how to pass the selected file.
Via urls, parameters can be passed, but I do not know how I can pass the path or URL of the video file as a parameter. Or can something like this be achieved via post requests and if so how?
Here are parts of my script (I don't use post request for this at the moment):
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input id="myFileInput" type="text">
<input class="button1" id="inputfield" name="upload" type="file" accept="video/*" onchange="document.getElementById('myFileInput').src = window.URL.createObjectURL(this.files[0]); document.getElementById('buttonStart').className = 'button'; this.form.submit()" value="Select a File"/>
</form>
The file path is stored in 'myFileInput'. But I could also get the file path through post request. Then I have the problem, that no class instance that I know where I could save that path and load it later.
<img id="demo" src="">
and the function for
function video_on() {
document.getElementById("demo").src = "{% url 'mask_feed' urlpath='path_I_would_like_to_pass' %}"; //
document.getElementById("wait").innerHTML = "Turning on. . . . .";
setTimeout(showText, 3000);
}
and the urls.py file:
path('mask_feed/<path:urlpath>', views.mask_feed, name='mask_feed'),
And of course I have a mask_feed method in my views.py that takes urlpath as argument.
How can I "insert" the file path I get with html insert into the Django template "{% url 'mask_feed' urlpath='path_I_would_like_to_pass' %}"?
I would like to do something like this:
document.getElementById("demo").src = "{% url 'mask_feed' urlpath='document.getElementById('myFileInput').src' %}"
But it doesn't work because of the quotation marks.
And if this is not the way to go, how should I do it?

Dynamically replace all urls to full absolute url in template

I have a template which I am going to send as an email.
Thus I need to have absolute full urls (along with protocol and domain name) instead of relative ones.
The content in the email is going to come dynamically from database (entered using ckeditor, so I CAN NOT do something like {{ protocol }}{{ domain_name }}{% static '' %}. This would work only for static files. However the media content uploaded via ckeditor will recide in media files and I have absolutely no control over it.
Also i cant use javascript as it is an email template.
Currently I have built a python function which scans the entire template after rendering and prepends the protocol and domain name to every src attribute in img tag and all href attributes.
I would like to know if any better way exists
You can use request.build_absolute_uri and make a custom template tag in order to used when rendering your mail template.
Example
#templatetags/url_helper.py
#register.simple_tag()
def full_uri(request, relative_url):
return request.build_absolute_uri(realtive_url)
Then ...
{# Some template.html #}
{% full_uri request some_img.url as full_img_url %}
<img src={{ full_img_url }} />

django, secondary data in subfolders

I am working on an informational site. I am attempting to access files in a subdirectory using data from the django db.
Ex: if the record.id = 1 and the file is desc.txt, I want to grab /1/desc.txt
I currently have two items that I'm trying to access this way. The image file will work if I hard code the location, but I haven't been able to get it to work from the record data. The other one, I'm trying to load a description file into a div using jQuery and .html(), and can't get it to work at all.
The relevant section of code:
{% if aRecord %}
{% load static from staticfiles %}
<h1>{{ aRecord.Name }}</h1>
<br/>
Born: {{aRecord.Birth}}<br/>
Died: {{aRecord.Death}}<br/>
<div id="descArea"><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/></div>
<script>
descfile = 'Authors/1/desc.txt';
$('#descArea').text(descfile);
$.get("{% static 'Authors/1/desc.txt' %}", function(data) {
$('#descArea').html(data);
});
</script>
<br/>
{% else %}
Requested author not found.
{% endif %}
This is the hard-coded version that works, but I need it to work from the aRecord data. The 1 in both cases should come from the record id, and the image filename in the img tag should as well.
It sounds like this is really a question about how to produce a file path from dynamic data. Is that the case? If so, you will probably need to use string substitution.
In order to produce a string like '/1/desc.txt' where the 1 is given by a record id, you could do something like this:
path = '/{}/desc.txt'.format(record.id).

Drupal 8 Twig Template: get relative or absolute path from URI

I have in a twig template an image url, like "public://path/to/image.png". I want to get "sites/default/files/path/to/image.png" to use it in the template.
I thought it should work with something like this:
{{ url ('public://path/to/image.png') }}
or
{{ file_uri_scheme ('public://path/to/image.png') }}
But all I get are errors. I know that the second one is a PHP function, but is there any chance to do it with TWIG?
You can use the twig function file_url to get a relative path:
{{ file_url('public://path/to/image.png') }}
Checkout the documentation under https://www.drupal.org/node/2486991
It accepts a uri and creates a relative path to the file. At least in Drupal 8.1.
Retrieving a URL to a page from a "path" is deprecated in D8. https://www.drupal.org/node/2073811
EDIT:
nah im wrong and just missunderstood the spelling ;/
the correct answer is: they are working on a twig extension.
i was searching for a way to get my image uri / urls and achieved it with
{{ node.field_image[delta].entity.url }}

django - how to apply custom template filter to absolute url

I am trying to write a small urlshortener app.
everything is set up well so far. now I am trying to apply the filter to the full url:
{{ request.build_absolute_uri }}{{ request.get_absolute_url}} gives me the full url. But if apply my filter like this:
href="{{ request.build_absolute_uri }}{{ request.get_absolute_url|shortenme}}"
my filter isnot getting anything because request.get_absolute_url is alone giving empty string.
only {{ request.build_absolute_uri }}{{ request.get_absolute_url}} is giving the full url I want. How can I apply my filter to the full url?
Requests do not have a get_absolute_url method.
You want to use request.path or request.get_full_path. The second includes any query string.
See the docs on request attributes for more info.