Introducci贸n a Flask
驴Qu茅 es Flask?
Creando tu primer "Hello, World" en Flask
Rutas y Plantillas con Jinja
Rutas y vistas en Flask
Plantillas con Jinja en Flask
Manejo de Formularios y Datos
Manejo de formularios en Flask
Bases de datos: SQLite y SQLAlchemy
CRUD: Crear y leer datos en Flask
CRUD: Actualizar datos en Flask
CRUD: Eliminar datos en Flask
Organizaci贸n del Proyecto y Mejoras
Estructura de proyectos en Flask
Blueprints en Flask
Notificaciones con Flash Messages
Integraci贸n de TailwindCSS en Flask
Seguridad y Testing
Gesti贸n de sesiones en Flask
Manejo de cierre de sesi贸n en Flask
Validaci贸n de formularios en Flask
Pruebas unitarias en Flask
Pr贸ximos pasos en Flask
You don't have access to this class
Keep learning! Join and start boosting your career
Forms are an essential part of web development, as they enable communication between users and servers. Mastering the handling of forms in Flask will allow you to create interactive and functional web applications that respond to the needs of your users. In this content, we will explore how to implement forms in Flask, process the submitted information and perform effective redirections between different views.
To start working with forms in Flask, we need to understand how a basic HTML form is structured and how it connects to our backend. The first step is to create an HTML file containing our form.
<!DOCTYPE html><html><head> <title>CreateNote</title></head></head><body> <h1>Createa new note</h1> <form method="post"> <label for="note">Note:</label> <input type="text" name="note" id="note"> <input type="submit" value="Create note"> </form></body></html></html>.
This form has key elements that we need to consider:
method="post"
attribute indicates that we will send data to the server.name="note"
is crucial as it is the identifier we will use in Python to access this value.name
attributes, since they can cause problems when accessing them from Python.Once the form is created, we need to configure a view in Flask that can display the form and process the submitted data.
In Flask, we need to set up a route that can handle both GET requests (to display the form) and POST requests (to process the submitted data). This is achieved by specifying the allowed methods in the route decoration.
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
@app.route('/create-note', methods=['GET', 'POST'])def CreateNote(): if request.method == 'POST': # Process form data note = request.form.get('note', 'Not found') print(note) # To verify that we are receiving the data return redirect(url_for('confirmation', note=note))
# If it is a GET request, display the form return render_template('note.html')
In this code:
/create-note
path to accept GET and POST methodsrequest.method
request.form.get('note')
It is important to note that request.form
is an object that contains all the fields sent from the form. We can access each field using the name we assigned to it in the HTML.
A common practice after processing a form is to redirect the user to another page. This avoids problems such as form redirection when refreshing the page and improves the user experience.
@app.route('/confirmation')def confirmation(): # Here we should display a template with the confirmation return "Test" .
To implement the redirect, we use two important functions:
redirect()
: Redirects the user to another URLurl_for()
: Generates the URL for a specific view function.The advantage of using url_for()
instead of typing the URL directly is that if we change the path name in the future, we don't have to update all references to that URL in our code.
return redirect(url_for('confirmation', note=note))
In this example, we are redirecting the user to the confirmation
view and passing the value of note
as a parameter in the URL. This allows the confirmation view to access this value and display it to the user.
To complete the workflow with forms, we need to display the received data in an HTML template. This is achieved by passing the data to the render_template()
function.
@app.route('/confirmation')def confirmation(): note = request.args.get('note', 'No note found') return render_template('confirmation.html', note=note)
In this code, we are:
note
from the URL parameters with request.args.get().
confirmation.html
template .
Then, in our HTML template, we can display the received value:
<!DOCTYPE html><html><head> <title>Confirmation</title> </head></head><body> <h1>Notecreated successfully</h1> <p>Yournote: {{ note }}</p></body></html></html>.
The use of {{ note }}
in the template allows us to insert the value of the note
variable that we pass from our view.
Handling forms in Flask is a fundamental skill for any web developer. With this basic knowledge, you can start creating interactive applications that receive and process data from users. Do you dare to implement your own forms system? Share your experiences and doubts in the comments.
Contributions 1
Questions 0
Want to see more contributions, questions and answers from the community?