Search code examples
pythonwtforms

Having trouble transforming a form IntegerField to an integer variable in order to use it at calculating date


TypeError: int() argument must be a string, a bytes-like object or a number, not 'IntegerField' HERE IS THE ERROR

from flask import Flask, render_template
from wtforms import IntegerField, SubmitField
from flask_wtf import FlaskForm
import datetime

app = Flask(__name__)

app.config['SECRET_KEY'] = 'alex'

class Calculator(FlaskForm):
    Year = IntegerField('Year')
    Month = IntegerField('Month')
    Day = IntegerField('Day')
    submit = SubmitField('Calculate')

tdy = datetime.date.today()

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


@app.route("/about")
def about():
    return render_template('about.html')

@app.route("/Calculator", methods=['GET', 'POST'])
def days():
    form = Calculator()
    return render_template('calculator.html', form=form)

@app.route('/HURRAY', methods=['GET'])
def ura():
    form = Calculator()
    y = int(form.Year)
    m = int(form.Month)
    d = int(form.Day)
    till_bday = tdy - datetime.date(y, m, d)
    return render_template('HURRAY.html', till_bday = till_bday)

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

The idea of the whole app is the following: You have a form, enter YEAR MONTH AND DAY in a IntegerField used with WTFORMS and when you click SUBMIT on that page you are redirected to a page where your result is shown. This sounds simple until I realized i have no idea how to make my IntegerField data in an integer variable that i can calculate and pass through my HTML file....


Solution

  • As you pointed out, you don't want the form's field themselves, you want the data sent along with the post request.

    On the "/calculator" page, when you click submit, a post request is sent to your server, with data containing the values of each field in your form. Now I'm not sure how it works in Flask, but you want to find:

    • Which route in your server this request has been sent to? (probably "/calculator" in this case, which seems to be the only route that accepts POST requests)
    • Within this route, how can you access the request sent to it, and the data sent with it?

    I'd recommend you have a clear understanding of how these HTTP requests work first (GET, and POST mainly) and how and where they are sent/received in your application.