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
Data validation is a fundamental aspect in web development that guarantees the integrity and quality of the information we receive from users. When building applications, especially those that allow the creation of content such as notes or publications, it is crucial to implement mechanisms that verify if the data entered meets our requirements before processing or storing it in the database.
When developing web applications, it is common for users to enter information that may not meet our validity criteria. For example, titles that are too short or content without enough information. Server-side validation is essential to ensure that only data that meets our requirements is processed.
In Flask, we can implement manual validations relatively easily. These validations are performed before the data is stored in the database, allowing us to display appropriate error messages to the user and avoid processing invalid information.
To implement basic validations in our Flask routes, we can check the conditions directly in the route code. Let's see a practical example:
@app.route('/notes/create', methods=['POST'])def create_note(): title = request.form['title'] content = request.form['content']
# Title validation if len(title.strip()) > 10: # Title is valid, we continue
# Content validation if len(content.strip()) > 300: # Content is valid, we save the note # Code to save the note in the database flash('The note was created successfully', 'success') return redirect(url_for('notes')) else: flash('The content is too short, minimum 300 characters', 'error') else: flash('The title is too short, minimum 10 characters', 'error')
# If we got here, there was a validation error return render_template('create_note.html')
In this code, we are validating two conditions:
If any of these conditions are not met, we display an error message to the user and re-render the form so that they can correct the information.
Flask includes a flash message system that allows us to send messages between requests. These messages are stored in the session and are displayed on the next request. In our example, we use this system to display error or success messages to the user:
flash('Title is too short, minimum 10 characters', 'error').
The second parameter ('error') indicates the type of message, which allows us to apply different styles depending on whether it is a success, error, warning, etc. message.
For these messages to be displayed correctly, we need to include the corresponding code in our base template:
{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert alert-alert-{{{ category }}"> {{ message }} </div> {% endfor %} {% endif %}{% endwith %}
This code goes through all flash messages and displays them with the CSS class corresponding to the message type.
Although manual validation is useful for simple cases, Flask offers integrations with more powerful libraries to handle complex validations. One of the most popular is Flask-WTF, which provides an integration between Flask and WTForms.
Flask-WTF allows you to define forms as Python classes, with declarative validation rules:
from flask_wtf import FlaskFormfrom wtforms import StringField, TextAreaFieldfrom wtforms.validators import DataRequired, Length
class NoteForm(FlaskForm): title = StringField('Title', validators=[ DataRequired(message='Title is required'), Length(min=10, message='Title must be at least 10 characters long') ]) content = TextAreaField('Content', validators=[ DataRequired(message='Content is required'), Length(min=300, message='Content must be at least 300 characters long') ])
This approach offers several advantages:
To use Flask-WTF in our routes, the code would be simplified:
@app.route('/notes/create', methods=['GET', 'POST'])def create_note(): form = NoteForm()
if form.validate_on_submit(): # All data is valid # Code to save the note to the database flash('The note was created successfully', 'success') return redirect(url_for('notes'))
# If there are validation errors, they will be automatically displayed in the template return render_template('create_note.html', form=form)
And in the template:
<form method="post"> {{ form.csrf_token }}
<div class="form-group"> {{ form.title.label }} {{ form.title(class="form-control") }} {% if form.title.errors %} <div class="errors"> {% for error in form.title.errors %} <span class="error">{{ error }}</span> {% endfor %} </div> {% endif %} </div>
<div class="form-group"> {{ form.content.label }} {{ form.content(class="form-control") }} {% if form.content.errors %} <div class="errors"> {% for error in form.content.errors %} <span class="error">{{ error }}</span> {% endfor %} </div> {% endif %} </div>
<button type="submit" class="btn btn-primary">Createnote</button></button></form>
Validation is not only about preventing incorrect data, but also about providing a good user experience. Some best practices include:
The combination of client-side (JavaScript) and server-side (Flask) validations provides the best experience and security, as client-side validations enhance the user experience while server-side validations ensure data integrity.
Data validation is an essential component of any robust web application. Implementing effective validations improves both the user experience and the quality of the stored data. We invite you to experiment with Flask-WTF and other validation libraries to improve your applications. What other validation rules do you consider important for a note application? Share your ideas in the comments.
Contributions 0
Questions 0
Want to see more contributions, questions and answers from the community?