Flask does not provide a direct boolean value for checkboxes

After struggling for a week, I am still lost on where to make changes in my code. I need the checkbox to return a boolean value in my Flask application. Below are snippets of the relevant code:

mycode.py

import os, sqlite3

from flask import Flask, flash, request, render_template, send_from_directory, g, session, abort, redirect, url_for
from random import randint
from tkinter.messagebox import *

import os, sqlite3

app = Flask(__name__)

app.config.from_object(__name__)

@app.route('/')
def home():
    return render_template('appvolti1.html')


@app.route('/filter')
def viewdb():
    global list1
    bool_occhiali_checked = request.form.get('occhiali')

    if bool_occhiali_checked:
        list1 = ["Hello", "World"]
    else:
        list1 = ["Oh no", "don't work"]

    return newpage()


@app.route('/newpage')
def newpage():
    return render_template('filter.html', listaimmagini = list1)


if __name__ == '__main__':
    app.debug = True
    app.run()

appvolti1.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Face Recognition</title>
<style>
@import url(http://fonts.googleapis.com/css?family=Exo:100,200,400);
@import url(http://fonts.googleapis.com/css?family=Source+Sans+Pro:700,400,300);

    body{
        background: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.65)); /* For Safari 5.1 to 6.0 */
        background: -o-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.65)); /* For Opera 11.1 to 12.0 */
        background: -moz-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.65)); /* For Firefox 3.6 to 15 */
        background: rgb(230, 230, 230); /* Standard syntax */

    }
    .div1{
        margin:0 auto;
        width:1400px;
        display:block;
    }
    .subdiv1{
        display: inline-flex;
        display: -webkit-inline-flex;
        width: 100%;
    }
    .subdiv2{
        margin: 0 auto;
        display: table;
        height: 200px!important;
    }
    .subdiv3{
        width:40%;
        margin: 0 auto;
        display: table;
    }   

    .invia{
        display: table-cell;
        vertical-align: bottom;
        padding: 120px;/*qui gli elementi sono tutti importanti, ti ho lasciato il padding per farlo staccare dalla parte inferiore del contenitore*/
    }


    .invia input[type=button]{
        width: 160px;
        height: 35px;
        background: #597ef9;
        border: 1px silver;
        cursor: pointer;
        border-radius: 2px;
        color: #fff;
        font-family: 'Exo', sans-serif;
        font-size: 16px;
        font-weight: 400;
        padding: 6px;
        margin-top:100%;
    }


    .invia input[type=button]:hover{
    opacity: 0.8;
    }

    .invia input[type=button]:active{
        opacity: 0.6;
    }

    .invia input[type=text]:focus{
        outline: none;
        border: 1px solid rgba(255,255,255,0.9);
    }


    .invia input[type=password]:focus{
        outline: none;
        border: 1px solid rgba(255,255,255,0.9);
    }


    .invia input[type=button]:focus{
        outline: none;
    }
    .checkbox{
        margin-left: 50%;
        width: 160px;
    }
    .checkbox div{
        color: #5379fa;
        font-family: 'Exo', sans-serif;
        font-size: 15px;
        font-weight:bold;
    }
    .checkbox div span{
        color: #fff !important;
    }   


</style>
</head>
<body>
    <div class="div1">
        <div class="subdiv1">
            <div class="subdiv2">

            <div class="subdiv3" style="width:20%;margin-right:0px;">
                                <div style="position:relative;">

                <div class= "checkbox">
                    <div><span>Features</span></div>
<div><input type="checkbox" name="glasses">Glasses</div> 


</div>

</div>
                <div class="invia" style="margin: 0 auto;" >
                    <input type="button" value="Apply Filters" style="margin-left: -125%;" onclick="location.href = 'http://127.0.0.1:5000/filter';"> 
                </div>
        </div>
    </div>
</body>

</html> 

filter.html

<!DOCTYPE html>
<html>
<head>
<style>
    body{

        background: rgb(230, 230, 230); /* Standard syntax */
    }
</style>
</head>

<body>

  {{listaimmagini}}

</body>
</html>

Answer №1

Ensure that you enclose the form tag using the post method and include a submit button. By doing so, instead of utilizing a submit button with onclick, it will trigger a POST request to the server...

<form action="." method="post">
  <input type="checkbox" name="occhiali">
  <input type="submit" value="submit">
</form>

Next, in your view function, incorporate this code snippet...

if request.method == "POST":
    is_checked = request.form.get('occhiali')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying Ajax-injected HTML with JQuery's editInPlace functionality

I have been successfully using the JQuery editInPlace plug-in on a static HTML page. However, I am facing an issue when trying to use the same plugin with HTML injected via an Ajax call. I have heard that using .on() like '$('.edit_inplace_fiel ...

Javascript/AJAX functions properly on the homepage, but encounters issues on other pages

For a client, I have recently created 4 websites using Wordpress. Each site includes a sidebar with a script that utilizes the Google Maps API to estimate taxi fares. Strangely, the script works perfectly on the home page of each site, but fails to funct ...

Using requestAnimationFrame to animate several independent objects

I'm currently working on animating two different objects: a square and a circle. Each object has its own button to initiate the animation, which involves moving the object from left to right. However, I've run into an issue where clicking on one ...

Align the image and caption at the center in Bootstrap 4

I am presenting a figure that includes an image along with a caption. Here is the code for reference: <figure class="figure"> <img src="../img/atmpressure.svg" class="figure-img img-fluid" alt="pressue plot"> <figcaption class="figure-c ...

The creation of transparent objects in THREE.js allows for a dynamic display of overlaid objects in the

Greetings, I am interested in creating a three.js room where the walls behind which objects are located (from the perspective of the camera) will become transparent with 50% opacity as I rotate the room. Allow me to elaborate: Visualize a scenario whe ...

Having trouble extracting tabular data using Selenium for web scraping, as the output is either an empty list or just the header

I've been attempting to scrape data from the page 'https://www.topuniversities.com/university-rankings/world-university-rankings/2022' in order to extract the table containing university rankings. Despite trying various methods such as findi ...

Calculating the time difference between the current datetime and a value retrieved from

I am having trouble calculating the difference between the current date and a date stored in my database. My goal is to display an expiry date message if the difference is 30 days. Here is the code snippet I currently have: var timeDifference = DateTime.N ...

Using CSS to center the text and adding a separator line in blank spaces for a clean and stylish look

Request to Create Centered Date Element with Line Borders I am looking to design an element where the date is positioned at the center, while two horizontal lines fill the empty space on either side. Ideal Design I Want to Achieve: My Current Approach a ...

Locate element using value in Selenium with Python

Currently, I am utilizing Selenium in conjunction with Python to autonomously extract data from various power plants. One challenge I am facing is the need to click on an element within each plant's unique interface. The difficulty lies in the fact th ...

The combination of AddEventListener in the parent and postMessage in the iframe is ineffective

As I delve into the Stripe documentation to develop a new feature, I have encountered an issue regarding the communication between a webpage and an iframe. The code in index.html: <!DOCTYPE html> <body> parent<br> <iframe src="./ ...

How can methods access variables from the Vuex store during function calls?

Within my Vue.js component, there is a v-select element. Upon user selection in this widget, the toDo function is triggered from the methods block. However, when attempting to access the value of the filters getter within this function, it consistently ret ...

Customizing the step function of HTML5 input number with jQuery: A guide

Is there a way to modify the step value in HTML5 number inputs for my web application? I would like it to increment and decrement by 100 instead of 1. I attempted the following approach: $("#mynumberinput").keydown(function(e){ if (e.keyCode == 38) / ...

After calling AJAX, jQuery fails to execute

Encountering an issue with JQuery on a dynamic page. I have a select input: <select id="select"> <option value="1">1</option> <option value="2">2</option> </select> and a text input: <input id="input" type= ...

Using opencv with selenium causes system crash

If I include the import cv2 statement, the Chrome browser launched by selenium fails to start with an error that doesn't seem related to opencv. All sanity checks have passed. Could it be that I'm overlooking something obvious here? Here is the ...

Converting RowDataPacket to an array in Node.js and MySQL API, learn how to convert a RowDataPacket from the MySQL API into an array

Hello, I need assistance with converting my row data packet into an array of arrays or nested arrays. Please provide code snippet below: router.get('/getPosts/:user_id', (req, res, next) => { connection.query('SELECT * FROM files WHERE ...

selecting a radio button and saving its value into a JavaScript variable

How can I assign the return value from a JavaScript script function to a variable inside the HTML body? The function will return the selected variable, but how can I assign it to a variable within my HTML body? <body> <form action="somepage.php ...

Having trouble with redirecting a website to its appropriate version for mobile or desktop users?

After creating both the desktop and mobile versions of my website, I have a question. How can I determine whether a visitor is using a mobile phone or a PC when they come to my website? Specifically, if a visitor accesses my website through a mobile devic ...

How to transform a string into a dictionary using a JavaScript variable in Python

I have extracted data from a webpage. I now have the content in this format, and I am looking to convert this object into a Python dictionary. JSON cannot be used here because it does not follow a valid JSON structure. { id: 37429, ...

The collapsible menu does not toggle when I tap on the icon

I am currently troubleshooting an issue with this link "https://sampledemos.online/training/index.html" where the toggle feature is not functioning properly. Below are the codes I have written: <aside id="layout-menu" class="layout-menu m ...

The Gulp task is failing to generate the CSS file

Greetings! I have a task set up in my gulpfile.js as shown below: const gulp = require('gulp'); const sass = require('gulp-sass'); gulp.task('sass', function(){ return gulp.src('sass/*.scss') .pipe(sass()) ...