wtforms, CSRF, flask, FieldList

前端 未结 4 1416
陌清茗
陌清茗 2020-12-10 12:14

I\'m having trouble passing through validation when using a FieldList with WTForms. I keep getting this error. {\'csrf_token\': [u\'CSRF token missing\'

相关标签:
4条回答
  • 2020-12-10 12:14

    After encountering the same problem, I wanted to to supply a third option to the solution above

    You can also override the constructor in your form class to replace the default value of csrf_enabled. This has the advantage that you can use the the same form definition as both a fieldlist member, and a standalone form with CSRF enabled by passing csrf_enabled=True.

    class FilterForm(wtf.Form):
        field = wtf.Form ...
    
        def __init__(self, csrf_enabled=False, *args, **kwargs):
            super(FilterForm, self).__init__(csrf_enabled=csrf_enabled, *args, **kwargs)
    
    0 讨论(0)
  • 2020-12-10 12:18

    Since version 1.0 the new way to achieve this is as follows: This will disable the CSRF token for all instances of your Form, so be careful to only use it as a subform.

    class MyForm(FlaskForm):
        class Meta:
            csrf = False
    
        myfield = StringField("A Field")
    
    0 讨论(0)
  • 2020-12-10 12:30

    The issue seems to be that Flask-WTForms Form is actually a subclass of wtforms.ext.SecureForm - and the only way to disable the csrf protection on a form is to pass the keyword argument csrf_enabled=False to the form when constructing it. Since FormField actually handles instantiating the form and you can either:

    • Create a subclass of FormField that will let you pass in form keyword arguments
      or
    • Subclass wtforms.Form rather than flask.ext.wtforms.Form for your FilterForm (as long as you never display a FilterForm on its own you won't need to worry about CSRF).
    0 讨论(0)
  • 2020-12-10 12:33

    It seems csrf_enabled is deprecated. Here's a solution that works with Flask-WTForms 0.14.2, partially based on leebriggs's answer. Rather than pass a parameter when creating the form, I just created a xNoCsrf subclass, because I didn't want someone to accidentally forget to include the CSRF token when they do want it. This way, you have to type NoCsrf to get the non-CSRF version.

    class FilterForm(FlaskForm):
        <some stuff here>
    
    class FilterFormNoCsrf(FilterForm):
        def __init__(self, *args, **kwargs):
            super(FilterFormNoCsrf, self).__init__(meta={'csrf':False}, *args, **kwargs)
    

    Here is the documentation for csrf field of the meta class.

    0 讨论(0)
提交回复
热议问题