How to check current URL/endpoint in django if statement - python

I have a button on a base template that just takes you back (history.back()) on every page except for one specific page. I assume there's a simple one line like {% if URL == specificURL %} but for the life of me I can't figure out how to do it.
Im trying to do it within the html, but I'll happily take any other suggestions if something else would work
Its a light site and I could take the button off the base template and just put separate logic on every html page but that's obviously bad for scale
should also probably preface that I'm definitely beginner for Django
edit: just thought of using a content block to change the base template in just the one page. Think that should work but I would still like to know if it can be solved my original way as id use that for other purposes

Related

How to pass a dynamically changing variable from python to HTML and get the browser to re-render the new data without reloading the whole web-page?

I would like to achieve the following:
pass a variable from my python script to a HTML page
get the browser to display the updated information
DO NOT re-render, or reload the WHOLE HTML page as this would take too long (new data will be transmitted from the python script to the HTML page every 250ms or so.)
data is generated live by the python script and so the solution have to take this into account
After researching the whole day and watching numerous tutorials, I understood that Flask or Django could be used to achieve this via a concept called "templating". Unfortunately I am complete beginner and I got lost in the details without seeing the "big picture" of what is need to be done...
So I ended up here, hoping someone can clear up my understanding about the topic without assuming any previous knowledge...
So I have a super simple HTML file as below:
<!DOCTYPE html>
<html>
<head>
<title>Simple Test</title>
</head>
<body>
<h1>Changing Number:</h1>
<h1 id="number">0</h1>
and I also have a python script:
import random
import time
for i in range(10):
myvar = random.randint(1, 10)
time.sleep(1)
The goal is to pass myvar to the html element with the id, "number" and have the browser display the new value without reloading the page.
Just to be clear I do not expect a comprehensive in-depth tutorial as I know that it would take too long to create, (if possible at all...), but instead I would like to get the "birds eye view", or the "big picture" on what I need to do.
Here is my current understanding (which is most likely incorrect):
I have to have a python file containing the script that calculates the
value to be passed. (I use VSCode on a windows based system to edit
this file)
I have to import Flask into this python file (if nothing better is
recommended) as this is the framework with the capacity to create
the "link" in between the python script and the HTML page
so:
python script calculates desired value ---> hands the value to flask ---> flask hands the value to the HTML document ---> browser renders the document
...but how does the process repeated when a new value is calculated by the python script?
How do I instruct the browser to re-render only the desired part of the web-page?
Is there a simpler way, or better framework that could do that task?
Am I looking in the right direction to solve the problem or should approach the problem from a different angle?
Many thanks in advance!
I don't think that's possible without using js. On a request, django renders the html and sends it back to the browser, so you gotta reload the page.

Problem getting value from a clicked-button, back to flask

I have multiple buttons, for a mobil platform tool. created from a dynamic list, using flask and python3.8. I can not seem to get the value from the button itself (a filename, to be used by the function call to start a specific script on the pi server.) The list itself is created fresh based on what files are in a specific directory, the web portal just creates a button for each file, in a clickable format. The desired result is after the click, html passes the filename back to python as a variable, to be executed by a function call.. I am fairly new to programming like this, so this is likely a simple thing for most of you, but I have been trying everything I can and can't get it to work, and google, in this particular case, is not my friend ;)
the x is a value from the list of files in the source dirtectory. all of this works as it should.if i set a static file name I can even start the file.
file.html
<h1>Available Menu</h1>
<p>###### #######</p>
<ol>{% for x in lr1 %}
<div class="flex-parent jc-center">
</div>
{% endfor %}
</ol>
<p> Please make your selection by clicking on it.</p>
I have gone through many differnt attempts at forms, sessions, etc... , but this is where I am right now. the first href if just for testing purposes, for site flow. The second one is the one I will be using for actual operations.
file.py
#app.route('/make', methods=['get', 'post'])
def makefile():
# make/run selected file.
sel_name = '' # needed input variable
### missing piece...
cmdgg = '/##########.sh /media/rbins/{}'.format({sel_name}) # script call
print(cmdgg)
subprocess.Popen(cmdgg, shell=True).wait()
print(f'######') # confirmation message
i have tried so many variations now, and none seem to cut it so I am not going to even complete this function, because I must be approaching it incorrectly. I have everything else working, i am only missing this one component... I am even open to just creating a text file in the root dir that I can parse to make the command, but again, I cant make that work either.. This is an area I still need to learn a bit more on.
Any assistance or suggestions would be greatly appreciated.
To avoid more confusion id suggest you to check out flask_wtf is used to creating forms and its exactly what you need in order to send data from client to back-end. Happy coding !

Is it possible to specify a page template for the first page and another for following pages in reportlab

I am building a fairly simple document in reportlab with platypus. It is basically a header on all the pages and then a table object with line items that will extend onto multiple pages.
What I am trying to figure out is if there is a way to specify one page template for the first page, and a page template for all following pages.
From what I can tell you have to put a call to NextPageTemplate as a flowable in your story, but since one flowable takes up multiple pages I can't put a NextPageTemplate call in there.
I thought there was a way to specify a template onFirstPage and a template onLaterPages when building the document but I can't seem to find that anymore.
Any Ideas?
Alright I figured it out. Hope this will help someone else in the future.
Where I had seen onFirstPage and onLaterPages was in the build method of the SimpleDocTemplate class. And while for a simpler report it would have worked fine, for mine that method does not work. I am using a frame to specify the margins of my document, there is probably a better way to do this, and the SimpleDocTemplate creates it's own margin Frame, also I might be wrong about that.
Anyways, I subclassed BaseDocTemplate to overide the handle_pageBegin method to tell the build method to switch to the second page template like so:
def handle_pageBegin(self):
'''override base method to add a change of page template after the firstpage.
'''
self._handle_pageBegin()
self._handle_nextPageTemplate('Later')
Then I could just add 2 page templates into the document when I create it naming the second one 'Later'.
Seems to work great for now.

Embed Flask page in another without code duplication?

I have a page (located at /games/compare/) and it's a mini image comparison game. Users are shown two images and asked to pick between them in response to a question. This page can get images from the database, render a template with javascript and css inside and communicate back to the database using AJAX.
Now what if I wanted to embed this voting game onto the main page without duplicating any code? Ideally, I'd update the game and all the pages that "feature" the game will also reflect the changes.
I'm getting hung up on how to manage the assets for the entire site in a coherent and organized way. Some pages have css, javascript and I'm also using frameworks like bootstrap and a GIS framework.
Would I set the game up as a blueprint? How would I organize the assets (Javascript and CSS) so that there is no duplication?
Currently, I have a page rendering a template (main.html) which extends another (base.html). Base.html includes header.html, nav.html and footer.html with blocks set up for body and others.
My current approach is to strip everything out at the lowest level and reassemble it at a highest common level, which makes coding really slow. For instance, I have that voting game and right now it's located in a page called voting_game.html and has everything in it needed to play the game (full page html, styles and javascript included). Now if I want to include that game on another page, like the root index, the only solution I know of is to strip out the style, js and full page html from voting_game.html, leaving only the html necessary for the game to run. When I'm creating the index now, I'll import the html from voting_game.html but I'll separately have to import the style and javascript. This means I have to build every page twice, which is twice the work I need to be doing. This process also leaves little files all over the place, as I'm constantly refactoring and it makes development just a bookkeeping nightmare.
There has to be a way to do this and stay organized but I need your help understanding the best way to do this.
Thanks,
Phil
Edit: The embedded page should also be able to communicate with its parent page (the one it is being embedded into), or with other embedded pages within the same parent (children of a parent should be able to talk. So when someone plays the embedded game, they earn points, which should show up on another part other page, which would update reflecting the users current points.
This "Score board" would also be a separate widget/page/blueprint that can be embedded and will look for certain pieces of data in order to function.
To re-use a chunk of HTML, you can use Jinja's {% include %} tag. If that's too limiting, Jinja macros are also well suited. You can define your macros in a separate file and import them with {% import "path/to/macros.html" as my_macros %}.
Flask-Assets can help with the organisation of your assets.
As for using Blueprints, yes you should use them. But they mostly apply to Python code and HTML templates are organised in a different realm, so maybe their use is unrelated here.
You can't always remove all duplication though. If your game needs to affect three distant locations of the server-generated HTML, that's bits of template code to copy in every template that includes your game.

Python Templating and Ajax

I was not able to come up with a better title for this post, so if anybody does not find it appropriate , please go ahead and edit it.
I am using flask as my python framework, and normally I render templates doing somnething like the below:-
#app.route('/home')
def userhome():
data=go get user details from the database
return render_template("home.html",userdata=data)
Now I have a template name home.html in which I iterate over the values of "userdata" like userdata.name, userdata.age etc and these values take their appropriate spaces in the template.
However I am working on an application in which navigation is via ajax and no fall back if javascript is not available(basically the app does not work for ppl without javascript).
The navigation menu has say few tabs on the left ,(home,youroffers,yourlastreads). The right column is supposed to dynamically change based on what the user clicks.
I am unable to understand how I handle templating here. Based on what the user clicks I can send him the required data from the db via a json through an xhrGET or xhrPOST.Does the entire templating have to be handled at the server end and then transfer the entire template via an ajax call. I actually dont like that idea much. Would be great if someone could point me in the right direction here.
Now in the page that is loaded via ajax , there are some scripts which are present. Will these scripts work, if loaded via ajax.
You have two options: template on the server, or template in the browser.
To template in the server, you create an endpoint much like you already have, except the template only creates a portion of the page. Then you hit the URL with an Ajax call, and insert the returned HTML somewhere into your page.
To template in the browser, your endpoint creates a JSON response. Then a Javascript templating library can take that JSON, create HTML from it, and insert it into the page. There are lots of jQuery templating solutions, for example.
I would choose server side templating, because unless you find a JS library that handles the same templating language your code isn't going go be DRY.
In the home.html template, I'd do something like
<%extends base.html%>
<%include _user_details.html%>
... <% footer and other stuff%>
And keep the actual markup in _user_details.html. This way, for an AJAX request you just render the _user_details.html partial only.

Categories