Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-WTF form posts successfully but validation never occurs

I have been struggling around the WTF forms for quite a while now. But this error, never seems to go away. I When ever I try to run this code the form never validates

Views :

@bundle.route('/content/add/', methods=['GET', 'POST'])
@bundle.route('/content/add', methods=['GET', 'POST'])
@bundle.route('/content/edit/<posturl>/', methods=['GET', 'POST'])
@bundle.route('/content/edit/<posturl>', methods=['GET', 'POST'])
@fas_login_required
def addcontent(posturl=None):
    form = CreateContent()
    form_action = url_for('content.addcontent')
    if posturl is not None:
        content = Content.query.filter_by(slug=posturl).first_or_404()
        form = CreateContent(obj=content)
        if form.slug.data == posturl and request.method == 'POST' and form.validate():
            form.populate_obj(content)
            db.session.commit()
            return redirect(url_for('content.addcontent',
                                    posturl=posturl, updated="True"))

    else:
        if request.method == 'POST' and form.validate():
            query = Content(form.title.data,
                            form.slug.data,
                            form.description.data,
                            form.media_added_ids.data,
                            form.active.data,
                            form.tags.data,
                            g.fas_user['username'],
                            form.type_content.data
                            )
            try:
                db.session.add(query)
                db.session.commit()
                # Duplicate entry
            except Exception as e:
                return str(e)
            return redirect(url_for('content.addcontent',
                                    posturl=form.slug.data, updated="True"))
        else:
            print "Please validate form"
    return render_template('content/edit_content.html', form=form,
                           form_action=form_action, title="Create Content")

Form Class :

# -*- coding: utf-8 -*-
from flask.ext.wtf import Form
from wtforms import TextField, TextAreaField
from wtforms import BooleanField, SelectField, validators
from wtforms.validators import Required

__all__ = ['CreateContent']


class CreateContent(Form):
    title = TextField(
        'Title',  [validators.Length(min=4, max=255)])
    slug = TextField(
        'Url-Slug', [validators.Length(min=4, max=255)])
    description = TextAreaField('Content', [validators.Length(min=4)])
    media_added_ids = TextField('media')
    type_content = SelectField(u'Content Type',
                               [Required()],
                               choices=[('blog', 'Blog Post'),
                                        ('media', 'Lecture'),
                                        ('doc', 'Documentation')]
                               )
    # Comma seprated media id's
    active = BooleanField('Published')
    tags = TextField('Tags', [Required()])
    # Comma seprated tag id's

And my Template :

    {% extends "base.html" %}
    {% block title %}
        {{ title }}
    {% endblock %}
    {% block content %}
    {% from "_formhelpers.html" import render_field %}
    <div id="Create Content">
        <center><h3> {{ updated }} </h3></center>
        <h2>{{  title  }}</h2>
        <form method="post" action="">
            <fieldset>
                <legend></legend>
                {{ render_field(form.title) }}
                {{ render_field(form.slug ) }}
                {{ render_field(form.description ) }}
                {{ render_field(form.media_added_ids)}}
                {{ render_field(form.type_content) }}
                {{ render_field(form.active) }}
                {{ render_field(form.tags )}}
        </fieldset>
        <input type="submit" class="button" value="Save"/>
    </form>
    </div>
    {% endblock %}

Any help will be highly apprieciated

like image 740
Hammad Haleem Avatar asked Dec 13 '25 23:12

Hammad Haleem


1 Answers

If the CSFR tokens are activated in a flask application setting, a CSFR token is included in each form. If developer has activated the setting and not included it in the form template the flask WTF would automatically reject the request.

The solution to this problem was to the following tag :

{{form.hidden_tag()}} 

Once added, a CSFR id is included in the request and sent to the views for validation by the WTForms.

If you haven't included this token no errors will appear in the form.errors dictionary. If you iterate over this dictonary no errors will be show, but the form.validate method will return false.

like image 138
Hammad Haleem Avatar answered Dec 15 '25 12:12

Hammad Haleem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!