Setting a gallery in amp lightbox with Django - python

I have been working on a project with Django on the back-end and amp on the front-end; although I am having some troubles to link both tags like the lightbox one.
I would like to get a list of first images on my product page (I have done it) and by clicking on an image it displays me the other images of that object on a lightbox without going to the detail template.
The whole project is updated on GitHub at:
https://github.com/lucasrf27/dealership
That is the amp code that I am trying to. I am trying this one on test.amp.html besides put on my category. (product template)
<body>
<h1>lucas</h1>
<div>
{% for v in veiculos %}
<h1>{{v.modelo}}</h1>
<amp-img lightbox="cars" src="{{ v.first_image.imagem.url }}" width="" height="" layout="fill" alt="{{v.modelo}}">
<amp-carousel lightbox="cars" width="350" height="350" type="slides">
<div>
{% for v in veiculos %}
<h1>{{v.modelo}}</h1>
<amp-img lightbox="cars" src="{{ v.first_image.imagem.url }}" width="300" height="400" alt="{{v.modelo}}">
<amp-carousel lightbox="cars" width="350" height="350" type="slides">
{% for p in veiculos.images.all %}
<amp-img lightbox="cars" src="{{p.imagem.url}}" width="" height="" layout="fill" alt="{{v.modelo}}"></amp-img>
{% endfor %}
</amp-carousel>
</amp-img>
{% endfor %}
</div>
</amp-carousel>
</amp-img>
{% endfor %}
</div>
<!-- These will belong to a different lightbox gallery -->
<div>
<amp-img lightbox="another" src="image3.jpg" width="400" height="300" layout="responsive"></amp-img>
<amp-img lightbox="another" src="image4.jpg" width="400" height="300" layout="responsive"></amp-img>
</div>
When I open the images from the lightbox on a new URL,
I get this one:
http://127.0.0.1:8000/veicles/image3.jpg (404)
However the image is in this one:
http://127.0.0.1:8000/media/veiculos_imagens/bugat-logo-whatsapp-fundo-transparente3.png
Is there some sort of media_prefix or something like that?

i've got the results in a silly way. besides setting on my views or my template a set up a object in function like i did in first_image but for the second and the other 2
it got like:
template
<body>
<h1>lucas</h1>
{% for v in veiculos %}
<amp-carousel lightbox width="1600" height="900" layout="responsive" type="slides">
<amp-img src="{{v.first_image.imagem.url}}" width="200" height="100"></amp-img>
<amp-img src="{{v.second_image.imagem.url}}" width="200" height="100"></amp-img>
</amp-carousel>
{% endfor %}
models:
def first_image(self):
return self.images.first()
def second_image(self):
return self.images.all()[1]
if anyone in the future is not understanding the project try to access:
https://github.com/lucasrf27/dealership

Related

Flask static image url won't generate

I'm having some trouble with getting Flask to serve images I downloaded.
Python:
r = requests.get(image_url)
with open(f"static/image{i}.jpg", "wb") as f:
f.write(r.content)
# Add the image to the list of images
images.append(f"image{i}.jpg")
return render_template('story.html', paragraphs=paragraphs, images=images)
Html:
<body>
<h1>Story</h1>
{% for paragraph in paragraphs %}
<p>{{ paragraph }}</p>
<img src="{{url_for('static', filename=images[i] }}">
{% endfor %}
Resulting page source code:
<h1>Story</h1>
<p>Once upon a time there was a young girl named Maria who was in a long distance relationship with her boyfriend, John. John lived in a different city and they could only see each other once every few months.</p>
<img src="/static/">
<p></p>
<img src="/static/">
<p>Whenever they met, they would talk and laugh and enjoy each other's company, but Maria couldn't help but feel like something was missing. She was feeling lonely and unsure about the future of their relationship.</p>
<img src="/static/">
<p></p>
<img src="/static/">
Not sure what I'm doing wrong.
The images array isn't empty, it prints all the image filenames. Also a bit weird that under each paragraph there are two images.
{% for paragraph in paragraphs %}
<p>{{ paragraph }}</p>
<img src="{{url_for('static', filename=images[loop.index]) }}">
{% endfor %}
This was the solution.

Django - show images with src from python list

I am trying to show few images on my website, I've collected the sources of all of them in a list. In html file I've created a loop to iterate through each of them.
HTML body :
<body>
<div class="content">
{% for output in outputs %}
<h1> {{ output }} </h1>
<img src="{% static '{{output}}' %}" alt="Mountains" style="width:100%">
<img src="{% static 'images/1.jpg' %}" alt="Mountains" style="width:100%">
{% endfor %}
</div>
</body>
So, the thing is - I am able to show image "1.jpg" from "images" directory (so the problem is not due to static files). I've also checked that "output" has the right content. This is the output of my code :
enter image description here
And this is directory where I store my images :
enter image description here
please, let me know if you have any idea what should i do next. Any advise will be helpful.
That's what worked for me, thanks to Abdul Aziz Barkat!
"Use {% static output %} not {% static '{{output}}' %} if you inspect the html you would see something like src="/static/{{output}}" for what you wrote.."

Flask - how to get id of post after clicking on title

I create a simply website about books. I display the title and description in books.html
<div id="book-container">
<p><h2>{{ b.title }}</h2></p>
<div><p>{{ b.description }}</p></div>
<br>
</div>
and my route file
#app.route('/show_books', methods=['GET', 'POST'])
def show_books():
books = Book.query.all()
return render_template('books.html', title='Home', books=books)
I have problem, because I want to display more information about book after clicking on title. What is the best way to do it? Thanks for help!
Ok, I find other solution but it doesnt work well:
book.html:
<div id="book-container">
{{ b.title }}
<div><p>{{ b.description }}</p></div>
<br>
</div>
routes.py:
#app.route('/detail_book/<title>')
def detail_book(title):
book = Book.query.filter_by(title=title).first_or_404()
return render_template('detail_book.html', book=book)
detail_book.html:
DETAILS
<div id="book-container">
{{ b.id }}
<h2>{{ b.title }}</h2>
<div><p>{{ b.description }}</p></div>
<br>
</div>
After clicking on title my url looks like:
http://localhost:5000/detail_book/Painted%20Man
And in consol: jinja2.exceptions.UndefinedError: 'b' is undefined
And I really have no idea how to solve this problem
You can use this to access the title you click. And this.id will give you the id of this element:
<div id="book-container">
<h2 id="{{ b.title}}" class="titles">{{ b.title }}</h2>
<div><p>{{ b.description }}</p></div>
<br>
</div>
<script type=text/javascript>
$(function(){
$('.titles').bind('click', function(){
alert(this.id);
});
});
</script>
By clicking on the title, you will see a modal indicating the id of the current element (in this case the id will be the title of the book).
The idea here is to add the class .titles to all the titles that will appear on your page and recover, with this.id, the id of the element you click. Then you can make an Ajax request to find the additional information corresponding to the specific element on which you clicked.
It looks like detail_book has a variable book not b.
In your render template you use the variable book.
Below is what the html should look like.
DETAILS
<div id="book-container">
{{ book.id }}
<h2>{{ book.title }}</h2>
<div><p>{{ book.description }}</p></div>
<br>
</div>

Running Flask environment using HTML:receiving error message of expected else statement

I am getting an error message as follows: TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.
I am using a Linux environment and this code should calculate interest rates.There are seperate files for running the scripts and the function.However once running the program i am getting an error message at the page stating that theres an expected else statement before the following code:
return render_template('interest_form.html', calc_total=True).
Below is the full code:
from server import app, valid_time
from flask import request, render_template
from Calculator import Calculator
#app.route("/", methods=["POST", "GET"])
def interest_total():
if request.method == 'POST':
initial=float(request.form["initial"])
rate=float(request.form["rate"])
time=float(request.form["time"])
Calculator.total_interest(initial,rate,time)
total=Calculator.total_interest()
return render_template('interest_form.html', total=total)
return render_template('interest_form.html', calc_total=True)
#app.route('/time', methods=["POST", "GET"])
def time_interest():
if request.method == 'POST':
initial=float(request.form["initial"])
rate=float(request.form["rate"])
total=float(request.form["total"])
Calculator.time_required(initial,rate,total)
time=Calculator.time_required()
return render_template('interest_form.html', time=time)
return render_template('interest_form.html', calc_time=True)
#app.route('/credits', methods=['GET'])
def credits():
return render_template('credits.html')
I am trying using a html form to send the input:
<!doctype.html>
<head><h2>Interest</h2><head>
<html>
<body>
<div>
<form action="routes.py" method='POST'>
<div style="margin: 10px 0px">
<label>Amount Invested ($): </label><br/>
<input name="initial" placeholder="Amount Invested"/>
</div>
<div style="margin: 10px 0px">
<label>Interest Rate (%): </label><br/>
<input name="rate" placeholder="Amount Invested"/>
</div>
<div style="margin: 10px 0px">
<label>Time Investment (Years): </label><br/>
<input name="time" placeholder="Amount Invested" {%if calc_time %}disabled{% endif %}/>
</div>
<div style="margin: 10px 0px">
<label>Total Interest ($): </label><br/>
<input name="total" placeholder="Amount Invested" {%if calc_total %}disabled{% endif %}/>
</div>
<div style="margin: 10px 0px">
<button type="submit">Submit</button>
</div>
<div><p>{{initial}} and {{time}}</p></div>
{% if total %}<h4>Total amount is<h4>
<textarea name="Amount" rows="5" cols="20"> {{total}} </textarea>
</form>
</div>
<div>
Time Form
Total Form
<br/>Credits Page
</div>
</body>
</html>
I have used a different template code that has a similar function and return format and when running it there seems to be no problem with it.This,however,seems to be showing the abovementioned error message.
(EDIT:I have updated the following code):
{% if total %}<h4>Total amount is</h4>
<textarea name="Amount" rows="5" cols="20"> {{total}}</textarea>
{% endif %}
</form>
Howver the error message is now showing: jinja2.exceptions.TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.
You need to close the if block in your template:
{% if total %}
<h4>Total amount is<h4>
<textarea name="Amount" rows="5" cols="20"> {{total}</textarea>
</form>
{% endif %}
Updated answer after the edit:
You need also an {% endblock %}at the end of the file for closing the {% block content %}at the top of the file.
I was getting a similar error - cause was a {% block content %} which I thought would not be affecting as it was commented out in HTML - turns out it was the culprit.
details:
jinja2.exceptions.TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'endblock'.The innermost block that needs to be closed is 'block'.
I know that each {% block content %} needs an {% endblock %} but what I didn't know was that if you have HTML comments around a {% block content %} , it doesn't work(i.e. it doesn't really get commented)
just putting it here in case anyone struggles the way I did for long before figuring it out.
below in my html code, although this was commented, it was the culprit that was giving me that exception.
`
<!--
{% block content %}
<table>
<tr valign='top'>
<td> <img src="{{ user.avatar(128) }}"></td>
-->
removing the {% block content %} from commented code solved it.
My half a day gone just breaking my head around it. Such a sad state, Jinja really sucks...the message was not clear, I literally had to run through the entire code to check for matching if/for what else... Now I removed all the comments from the page and it worked.. There were no blocks inside such comments..even then it worked... Angry with Jinja...

Can We use page breaks in for loops?

I wanted to print barcodes using for loop in python. This is my code:
`{%- from "templates/print_formats/standard_macros.html" import add_header -%}
<hr>
{% set a = doc.end %}
{% set count = 0 %}
<div class="row">
{%- for i in range(doc.start,doc.end) -%}
<div class="col-md-4 text-center">
<p style="font-family: Code39AzaleaFont;font-weight: normal;font-style: normal;font-size:30px;">
00000000000000{{ i }}</p>
{% set count = count + 1 %}
{{count}}
<br/>
</div>
{%- endfor -%}
</div>
<hr>
<br>
<p class="strong">
<br>
<br>
<br>
{{ _("Authorized Signatory") }}
</p>
</div>`
The problem is,I wanted to restrict the number of barcodes printed on one sheet of paper to 24.Is there any way to do that?
You can add a page break after every 24th barcode using:
{% if count % 24 %}<div style="page-break-before: always;"></div>{% endif %}
HTML doesn't have a really good concept of "paper sheet size". A HTML page has an infinite height and browser's are notoriously bad a printing HTML in a readable way (with the notable exception of Opera).
With CSS 3, three page break properties were defined.
They might be supported by your browser. If they are, then wrap 24 bar codes in a <div> and give that <div> a class which tells the browser to break the page afterwards.
If the browser emits an empty page at the end, then you need two classes: One for the first <div> without a page break and one for every successive <div> and a page-break-before: always;
If that doesn't work well, you should look at PDF. PDF allows you place elements exactly on pages with a known, fixed size.

Categories