You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

2 D铆as
18 Hrs
14 Min
13 Seg
Curso de Flask

Curso de Flask

Luis Mart铆nez

Luis Mart铆nez

Manejo de formularios en Flask

5/18
Resources

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.

How to create and process forms in Flask?

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:

  • The method="post" attribute indicates that we will send data to the server.
  • The field name="note" is crucial as it is the identifier we will use in Python to access this value.
  • Avoid using names in English or with special characters in the 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.

How to configure the routes to handle forms?

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:

  1. We import the necessary functions from Flask.
  2. Configure the /create-note path to accept GET and POST methods
  3. Verify the type of request with request.method
  4. We access the form data with request.form.get('note')
  5. Redirect the user to a confirmation page with the received data.

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.

How to implement redirects between views?

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:

  1. redirect(): Redirects the user to another URL
  2. url_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.

How to display the received data in an HTML template?

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:

  1. Getting the value of note from the URL parameters with request.args.get().
  2. Passing that value to the 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

Sort by:

Want to see more contributions, questions and answers from the community?

Hasta ahora me est谩 gustando m谩s este curso que el anterior :D