formsvalidationflaskflask-sqlalchemyflask-wtforms

In Flask why when you try to validate the information recieved, the logic doesn't validate the form?


I hope you are good.

I am having problems adding data to the database, when you as user, try and subimit a form, it sends it using method = "POST" which works fine, but when it trys to validate it with the forms, it doesn't work.

This is my html form code:

  <form method="POST" action="/contacto">
    <input name="name" type="text" class="feedback-input" placeholder="Nombre" />   
    <input name="email" type="text" class="feedback-input" placeholder="Email" />
    <input name="phone_number" type="text" class="feedback-input" placeholder="Teléfono" />
    <textarea name="message" class="feedback-input" placeholder="Mensaje"></textarea>
    <input type="submit" value="Enviar"/>
    <div class="check_aviso">
    </div>
</form>

This is my routes.py code:

@app.route('/contacto', methods=['GET', 'POST'])
def contacto():
    form = ContactInfoForm(request.form)
    context = {
        'form': form,
    }

    if request.method == 'POST':
        print("information sent via post")
        context['go_to_form'] = True

        if form.validate():
            print("also validated")
            name = form.name.data
            print(name)
            email = form.email.data
            phone_number = form.phone_number.data
            message = form.message.data
            user_info = ContactInfo(name=name, email=email, phone_number=phone_number, message=message)
            db.session.add(user_info)
            db.session.commit()
            send_contact_info_email(name, email, phone_number, message)
            flash(
                'Muchas gracias por la información, en la brevedad '
                + 'nos pondremos en contacto con usted.','success'
            )
            return redirect(
                url_for('contacto', _anchor='form')
            )
        else:
            flash('Data not saved','error')
        
        return render_template('contacto.html', **context)
    
    return render_template('contacto.html', **context)

This is my forms.py:

class ContactInfoForm(FlaskForm):
    name = StringField('Nombre')
    email = StringField('Correo electrónico', validators=[Email()])
    phone_number = StringField('Número de teléfono')
    message = StringField('Mensaje')

and this is my models.py:

class ContactInfo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    email = db.Column(db.String, nullable=True)
    phone_number = db.Column(db.String, nullable=True)
    message = db.Column(db.String, nullable=True)
    contact_date = db.Column(
        db.DateTime, nullable=False, server_default=db.func.now()
    )

the data is not validated, therefore its not added/saved into the database.


Solution

  • I'm assuming that no CSRF token is sent and that's why validation fails.
    The following example adds a hidden field with the token. In addition, errors are displayed during validation, which simplifies both debugging and handling for users.

    from flask import (
        Flask, 
        flash, 
        redirect, 
        render_template, 
        request, 
        url_for
    )
    from flask_sqlalchemy import SQLAlchemy 
    from flask_wtf import FlaskForm
    from wtforms import StringField
    from wtforms.validators import Email
    from wtforms.widgets import TextArea
    
    app = Flask(__name__)
    app.config.from_mapping(
        SECRET_KEY='Your secret here!', 
        SQLALCHEMY_DATABASE_URI='sqlite:///demo.db' 
    )
    db = SQLAlchemy(app)
    
    class ContactInfo(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String, nullable=False)
        email = db.Column(db.String, nullable=True)
        phone_number = db.Column(db.String, nullable=True)
        message = db.Column(db.String, nullable=True)
        contact_date = db.Column(db.DateTime, nullable=False, server_default=db.func.now())
    
    class ContactInfoForm(FlaskForm):
        name = StringField(
            'Nombre', 
            render_kw={ 'placeholder': 'Nombre', }
        )
        email = StringField(
            'Correo electrónico', 
            validators=[Email()], 
            render_kw={ 'placeholder': 'Email', }
        )
        phone_number = StringField(
            'Número de teléfono', 
            render_kw={ 'placeholder': 'Teléfono', }
        )
        message = StringField(
            'Mensaje', 
            widget=TextArea(), 
            render_kw={ 'placeholder': 'Mensaje', }
        )
    
    with app.app_context():
        db.drop_all()
        db.create_all()
    
    @app.route('/contacto', methods=['GET', 'POST'])
    def contact():
        form = ContactInfoForm(request.form)
        if form.validate_on_submit():
            contact_info = ContactInfo()
            form.populate_obj(contact_info)
            db.session.add(contact_info)
            db.session.commit()
            # ...
            flash(
                'Muchas gracias por la información, en la brevedad '\
                'nos pondremos en contacto con usted.','success'
            )
            return redirect(url_for('.contact', _anchor='form'))
        return render_template('contact.html', **locals())
    
    <form method="POST">
        {{ form.csrf_token }}
        <div>
            {{ form.name.label() }}
            {{ form.name(class_='feedback-input') }}
            {% if form.name.errors -%}
            <ul>
                {% for error in form.name.errors -%}
                <li>{{ error }}</li>
                {% endfor -%}
            </ul>
            {% endif -%}
        </div>
        <div>
            {{ form.email.label() }}
            {{ form.email(class_='feedback-input') }}
            {% if form.email.errors -%}
            <ul>
                {% for error in form.email.errors -%}
                <li>{{ error }}</li>
                {% endfor -%}
            </ul>
            {% endif -%}
        </div>
        <div>
            {{ form.phone_number.label() }}
            {{ form.phone_number(class_='feedback-input') }}
            {% if form.phone_number.errors -%}
            <ul>
                {% for error in form.phone_number.errors -%}
                <li>{{ error }}</li>
                {% endfor -%}
            </ul>
            {% endif -%}
    
        </div>
        <div>
            {{ form.message.label() }}
            {{ form.message(class_='feedback-input') }}
            {% if form.message.errors -%}
            <ul>
                {% for error in form.message.errors -%}
                <li>{{ error }}</li>
                {% endfor -%}
            </ul>
            {% endif -%}
        </div>
        <button type="submit">Enviar</button>
    </form>