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

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 !

Related

How to check current URL/endpoint in django if statement

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

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.

Detect changes in html using Django?

First of all, I'm very very new to web development (a few days), so I might say something that doesn't make sense.
I am writing a music web app using Django and I want to display a piano keyboard, have the user play some keys and then be able to retrieve this data (the notes the user played). I was able to embed the piano thanks to this, but I don't know how to get the data back. I tried wrapping the html key tags (<li class="key">...</li>) within a form tag and a submit bottom but I can't get it to work properly, and I'm not even sure if it's possible this way.
Then I realized, when you press some key, the tag's class changes from class="key" to class="key.active", so I was wondering if there is a way to detect these changes in the .html and thus be able to store the data. Does this even make sense? Maybe write a .py script to read the .html as a string and look for this changes? But does the .html file stored in the server change, or does it only change on the user's browser? I haven't found any info on the matter, which makes me think it might not be possible...

Django - turn field into tags with dropdown

In my form on django, I have a field called package_includes and a field called price. Right now, the content in package_includes it is simply text. So if I input "paper, glue, glitter" it will display exactly as i typed it, unable to change anything. However, I want the text to work like individual tags ->How I want tags to look
So when you click on one of the individual items (EX: "paper", "glue", or "glitter") i want it to display a drop down that allows you the option to put extra glitter for an additional $2.00 to the total.
Also, at the end of the text I want a tag that displays "Add" and this function would allow you to add items not included in this specific package. For example, you should be able to add crayons for $5, highlighter for $2.50, etc.
I am new to programming and don't fully understand how to add a function to text like this in a field in django. Thank you in advance for your help!
The answer to your question is unfortunately not a step-by-step instruction of how to go from 0 to a complete working example - only a pointer in the right direction.
What you need is achieved through CSS (producing the visual effect you want) and JavaScript (handling the drop-down functionality; it most probably has to be your own script based on jQuery). All of what you want needs to live (execute) within the Internet browser, and Django can only help there by serving the static CSS and script files, and referencing them in the actual page, when you put them in the correct template.
Here is an example of Wagtail Admin doing something similar:
If you open the page source in your browser, all you will see as HTML code for this is the following:
<div class="field-content">
<div class="input ">
<input id="id_tags" name="tags" type="text" value=""hello world", blog" /><script>initTagField("id_tags", "/admin/tag-autocomplete/");</script>
<span></span>
</div>
</div>
But if you open the page with FireBug, your browser's Development Tools, or the Web Developer extension, with visual styles applied it will decompose to something like this:
If you notice, the applied style to the form input element is display: none;. What you see is actually the styled unordered list elements right after. In order to be able to use them in your script, you need to be able to get to them/their contents from within your JS function. One strategy would be to assign an id attribute to all of the visible <li> elements. It can be something counter-based (e.g. id="shopping-cart-item-0", id="shopping-cart-item-1", etc.). Another way would be to assign an id to the <div class="input"> element, and within your function get all its DOM descendants of type <li>. Whatever works better for you. Then you could parse the label (inner text) of the list element in your script to get the type of item you are dealing with, and from then on find the discount price and apply it...
I would suggest that you start with a working example - find some app that uses taggit or similar package for Django and install it in a test application. Then you can use your browser's or preferred web development extension to play around with the CSS on them and see how different options affect the visual aspect of what you need. Once you are comfortable with that, see how you can build drop-down menus with jQuery. I believe the jQuery site has enough tutorials on the topic.

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.

Categories