In this blog, we will learn how to creating web form using flask with Jinja 2, before start to creating the flask web form first need to install it in our system.
Form structure:
Here we using pip command to install the flask:
> pip install flask
In this blog, we have using WTF web form library to creating the form, so that need to install the wtf- form
> pip install Flask-WTF
We can do it with proper way in which need to create some files like, __init__.py, routes.py, form.py, and configure.py
Using a virtual environment :
C:\Users\Admin\FlaskProjects\mkdir myform
C:\Users\Admin\FlaskProjects\cd myform
Now creating the virtual environment
C:\Users\Admin\FlaskProjects\cd myform\python3 -m venv venv
you can create a virtual environment with the following command:
C:\Users\Admin\FlaskProjects\cd myform\virtualenv venv
Now you can go to the venv directory and inside script, you can activate the virtual environment(C:\Users\Admin\FlaskProjects\myform\venv\Scripts)
C:\Users\Admin\FlaskProjects\myform\venv\Scripts\activate
Press Enter now your virtual environment activated, see below
Virtual environment activate
(venv) C:\Users\Admin\FlaskProjects\myform\venv\Scripts>
After this install the flask:
(venv) C:\Users\Admin\FlaskProjects\myform\venv\Scripts>pip install flask
Now creating a package which name is "app", it uses to execute your project
Now go to the app directory and here u create two python files:
__init__.py and routes.py
__init.py
app/__init__.py:
#--------------------code-----------------------
from flask import Flask
#from config import Config
app = Flask(__name__)
app.config['SECRET_KEY'] = 'you-will-never-guess'
from app import routes
#------------------------------------------
app/routes.py:
#----------------------code-----------------------
from flask import render_template, flash, redirect, url_for
from app import app
from app.forms import LoanForm
@app.route('/index', methods=['get', 'post'])
def index():
form = LoanForm()
#return render_template('index.html', title='Loan', form=form)
if form.validate_on_submit():
name = form.name.data
gender = form.gender.data
married = form.married.data
dependents = form.dependents.data
education = form.education.data
selfemployee = form.selfemployee.data
applicantincome = form.applicantincome.data
coapplicantincome = form.coapplicantincome.data
loanamount = form.loanamount.data
loanamountterm = form.loanamountterm.data
credithistory = form.credithistory.data
propertyarea = form.propertyarea.data
print(name)
print(gender)
print(married)
print(dependents)
print(education)
print("\nData Received")
flash("Message Received", "success")
return redirect(url_for('index'))
return render_template("index.html", form = form)
#------------------------------------------
app/forms.py
#------------------------code-------------
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, BooleanField, SubmitField
from wtforms.validators import DataRequired
class LoanForm(FlaskForm):
name = StringField('name', validators=[DataRequired()])
gender = StringField('gender', validators=[DataRequired()])
married = StringField('married')
dependents = IntegerField('dependents')
education = StringField('education')
selfemployee = StringField('selfemployee')
applicantincome = IntegerField('applicantincome')
coapplicantincome = StringField('coapplicantincome')
loanamount = IntegerField('loanamount')
loanamountterm = IntegerField('loanamountterm')
credithistory = StringField('credithistory')
propertyarea = StringField('propertyarea')
submit = SubmitField('Submit')
#--------------------------------------
After this create another python file “myform.py” where app folder exitst.
It used to store application instance with single line code
myform.py
#--------------
from app import app
#-------------------
Now go to the Script dir and run below command:
(venv) C:\Users\Admin\FlaskProjects\site1\venv\Scripts> set FLASK_APP=myform.py
this is used to run the app directly using<flask run> command
After this create another python file “configue.py” where app folder exitst.
It used to store application instance with single line code
#-------------------code-------------------
import os
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
#---------------------------------
Creating another folder "templates" in which all the HTML file is creating for web form design
Structure fo files:
site1=myform(change name)
templates/index.py:
#-----------------------------------code-----------------------
{% block content %}
<h1>Loan</h1>
<form action="" method="post" novalidate >
{{ form.hidden_tag() }}
<p>
{{ form.name.label }}<br>
{{ form.name(size=32) }}
</p>
<p>
{{ form.gender.label }}<br>
{{ form.gender(size=32) }}
</p>
<p>
{{ form.married.label }}<br>
{{ form.married(size=32) }}
</p>
<p>
{{ form.dependents.label }}<br>
{{ form.dependents(size=32)}}
</p>
<p>
{{ form.education.label }}<br>
{{ form.education(size=32) }}
</p>
<p>
{{ form.selfemployee.label }}<br>
{{ form.selfemployee(size=32)}}
</p>
<p>
{{ form.applicantincome.label }}<br>
{{ form.applicantincome(size=32) }}
</p>
<p>
{{ form.coapplicantincome.label }}<br>
{{ form.coapplicantincome(size=32)}}
</p>
<p>
{{ form.loanamount.label }}<br>
{{ form.loanamount(size=32) }}
</p>
<p>
{{ form.loanamountterm.label }}<br>
{{ form.loanamountterm(size=32)}}
</p>
<p>
{{ form.credithistory.label }}<br>
{{ form.credithistory(size=32)}}
</p>
<p>
{{ form.propertyarea.label }}<br>
{{ form.propertyarea(size=32)}}
</p>
<p>{{ form.submit() }}</p>
</form>
{% endblock %}
#----------------------------------------------------------------
Run using cmd with the path where all files exist:
C:\Users\Admin\FlaskProjects\myform\venv\Scripts\app> flask run
Without using a virtual environment:
Here no need to creating any virtual environment only need to create one folder in which you need to install flask at any location in our system
Need to create two-three files forms.py, routes.py and index.py(inside templates):
File structure:
#------------------------------------code----------------------
from flask import render_template, flash, redirect, url_for
from flask import Flask
import forms
#from app import app
#from forms import LoanForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'you-will-never-guess'
@app.route('/index', methods=['get', 'post'])
def index():
form = forms.LoanForm()
#return render_template('index.html', title='Loan', form=form)
if form.validate_on_submit():
name = form.name.data
gender = form.gender.data
married = form.married.data
dependents = form.dependents.data
education = form.education.data
selfemployee = form.selfemployee.data
applicantincome = form.applicantincome.data
coapplicantincome = form.coapplicantincome.data
loanamount = form.loanamount.data
loanamountterm = form.loanamountterm.data
credithistory = form.credithistory.data
propertyarea = form.propertyarea.data
print(name)
print(gender)
print(married)
print(dependents)
print(education)
print("\nData Received")
return redirect(url_for('index'))
return render_template("index.html", form = form)
if __name__ == '__main__':
app.run()
#----------------------------------------------------------
#---------------------code-------------------------------
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, BooleanField, SubmitField, FloatField
from wtforms.validators import DataRequired, InputRequired
class LoanForm(FlaskForm):
name = StringField('name', validators=[DataRequired()])
gender = StringField('gender', validators=[DataRequired()])
married = StringField('married')
dependents = IntegerField('dependents')
education = StringField('education')
selfemployee = StringField('selfemployee')
applicantincome = FloatField('applicantincome', validators=[InputRequired()])
coapplicantincome = FloatField('coapplicantincome', validators=[InputRequired()])
loanamount = FloatField('loanamount', validators=[InputRequired()])
loanamountterm = FloatField('loanamountterm', validators=[InputRequired()])
credithistory = StringField('credithistory')
propertyarea = StringField('propertyarea')
submit = SubmitField('Submit')
#-------------------------------------------------------------
templates/index.py
#-------------------------code------------------------------
Write above index.py code
#------------------------------------------------------------
Open cmd and run using a given path where these files are exist
C:\Users\Admin\FlaskProjects\app\> python routes.py
Serving Flask app "site1.py"
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
copy and paste this URL into the web browser and enter using given route.
Comments