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

Node.js Export Module Error - importance of separating concerns

I have been attempting to implement separation of concerns by using export module. Everything functions properly when used without separating concerns, but as soon as I try to import generateUrlArray() from const db = require('../db'), nothing se ...

Tips for opening a new browser tab

I'm having trouble getting my code to open in a new browser tab. Can someone help me figure out what's wrong? function getWaterMeterList() { // alert("ON"); var BillingPeriod = $('#BillingPeriod').val(); $.ajax({ ur ...

Adding a data attribute to a Material-UI Button: A step-by-step guide

I'm trying to include a custom data attribute in the Material-UI Button Component as shown here. Here's what I attempted: <Button inputProps={{ 'data-testid'='clickButton' }} > Click </Button However, this approach ...

Using jQuery to target a specific item from a retrieved list of elements

I'm currently working on a photo gallery feature that is reminiscent of Instagram or Facebook user photos. My goal is to enable users to view details about each image (such as the date) in a box that appears over the image when they hover over it. E ...

Searching for a method to locate and substitute a specific HTML string using the `sed` command in the macOS Catalina terminal

I am attempting to modify the following html code: <svg xmlns="http://www.w3.org/2000/svg" width="20" viewBox="0 0 256 256"> to this updated version: <svg xmlns="http://www.w3.org/2000/svg" width="30&q ...

Adjust css style based on the current time of day

I recently came across this fascinating tutorial that demonstrates an animation changing from day to night every 30 minutes. The concept is very appealing, but I began contemplating how to adapt this animation to reflect real-time changes between day and ...

When a user clicks on a child element of an anchor tag, the function will

Is it possible to return a specific function when a user clicks on a child of an anchor element? <a href="/product/product-id"> I am a product <div> Add to favorites </div> </a> const handleClick = (event) =>{ ...

Difficulty Establishing a Connection with SQL Server Using TypeORM

My local machine is running an SQL Server instance, but I'm encountering an error when trying to connect a database from TypeORM. The error message reads: originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (seque ...

Ways to attach JQuery UI Sortable widget to html content fetched through Ajax requests?

Here's a straightforward question for you. Take a look at my JavaScript/jQuery code snippet below: $('body .combo-table').sortable({ handle: '.grabber', opacity: 0.9, axis: 'y', start: function (e, ui) { ...

Tips for manipulating JSON data in Azure Data Factory

Received the data in env_variable.json using a Lookup variable and looking to extract "NO" and "BR" programmatically for iteration within a ForEach activity. The content of the file is as follows: { "countries" : { "NO" : { "wells": ["0015/abcd"] }, "BR" ...

Ensure that the div extends to the bottom of the page

I'm currently working on a web design assignment for one of my courses, and I'm facing some challenges with getting the div elements to span the entire page in terms of color. http://jsfiddle.net/vmm1s4Lt/ http://codepen.io/bmxatvman14/pen/fih ...

Ensuring Navigation Elements Remain Aligned in a Single Line

I'm in the process of developing an interactive project that will be showcased on a touch screen. One of its key features is a fixed footer navigation. Currently, I am using floats to position the main navigation elements and within each element, ther ...

Increment Counter on Presence of Items in a Table with jQuery

Does anyone know how to properly increment a counter in jQuery based on certain words found within a table? I am currently encountering an issue where my counter is only increasing by 1 instead of the expected 2. Here is the HTML and jQuery code snippet: ...

Angular Inner Class

As a newcomer to Angular, I have a question about creating nested classes in Angular similar to the .NET class structure. public class BaseResponse<T> { public T Data { get; set; } public int StatusCo ...

Unable to view mobile version on HTML page / lack of responsiveness observed

<body> <nav class="navbar navbar transparent"> <div class="container-fluid logo"> <div class="navbar-header"> <a class="navbar-brand" href="#"> <img src="images/Logo.png" /> & ...

What is the best way to determine the size of a returned element in React?

How can I determine if the description of {book.volumeInfo.description} is empty or not? If the length of {book.volumeInfo.description} is greater than zero, display it; otherwise, show "Book without description". I am unsure of the correct way to get the ...

Utilize the appendTo() function and make a switch to dynamically insert content stored in variables into a specified

I am working on developing a page with a central content div, where users have the ability to choose various options that will introduce different additional content. This added content will then present more opportunities for adding new elements, ultimate ...

Using JavaScript, concatenate text from each line using a specified delimiter, then add this new text to an unordered list element

I am looking to extract text from named spans in an unordered list, combine them with a '|' separating each word within the same line, and append them to another ul. Although my code successfully joins all the words together, I'm struggling ...

Collect information using Python's request module

import requests from pprint import pprint headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36', } params = ( ('LeagueID', &ap ...

The JavaScript confirm function will provide a false return value

Is it necessary to display a confirmation message asking "Are you sure ..."? I have implemented the message, but the function return false; is not working when the user clicks NO. <script> function confirmDelete(){ var answer = confirm("Are you su ...