Simple integration of Flask and WTForms, including CSRF, file upload and Recaptcha integration.

Overview
Comments
  • Validation (FileAllowed) issue upgrading 0.13.1 -> 0.14

    Validation (FileAllowed) issue upgrading 0.13.1 -> 0.14

    I upgraded Flask-WTF last night from 0.13.1 -> 0.14

    The issue I have is that when the FileField is blank (if the user chooses not to upload an image) then the validation fails. I do not require the field.

    class PostForm(FlaskForm):
        """Handle the input from the web for posts and replies."""
        body = TextAreaField('Post')
    
        upload = FileField('Upload', [
            FileAllowed(['gif', 'jpg', 'jpeg', 'png'],
                        'Only "gif", "jpg", "jpeg" and "png" files are supported')
        ])
    
        permission = RadioField('Permission', choices=[
            ('0', 'Public'),
            ('1', 'Pjuu'),
            ('2', 'Approved')
        ], default=0)
    
        def validate_body(self, field):
            if len(field.data.strip()) == 0 and not self.upload.data:
                raise ValidationError('Sorry. A message or an image is required.')
    
            if len(field.data.replace('\r\n', '\n')) > MAX_POST_LENGTH:
                raise ValidationError('Oh no! Posts can not be larger than '
                                      '{} characters'.format(MAX_POST_LENGTH))
    

    If I do this through my test suite all is okay using the following code:

    resp = self.client.post(
        url_for('posts.post'),
        data={
            'body': 'Test',
            'upload': '',
        },
        follow_redirects=True
    )
    

    The the post is successful. However if I make the request through Firefox (or Chrome) the validation is triggered saying I have an invalid format.

    Request body:

    Content-Type: multipart/form-data; boundary=---------------------------138689464934064453715802001
    Content-Length: 651
    
    -----------------------------138689464934064453715802001
    Content-Disposition: form-data; name="body"
    
    Test
    -----------------------------138689464934064453715802001
    Content-Disposition: form-data; name="csrf_token"
    
    IjY4YTZmYjNmNWM4MWJlNmVjMjc3Y2Y4YjBiMTM1Nzk3YTdhMGZkNjci.C1Vusg.RCp4SBZKai60nRqMGYP63i8JfXM
    -----------------------------138689464934064453715802001
    Content-Disposition: form-data; name="permission"
    
    0
    -----------------------------138689464934064453715802001
    Content-Disposition: form-data; name="upload"; filename=""
    Content-Type: application/octet-stream
    
    
    -----------------------------138689464934064453715802001--
    

    This was happening before I fixed the deprecation warnings that FileField is getting removed and to use the built-in WTForms FileField and after I changed the code to use this.

    I believe it's something to do with this change but can't find any documentation.

    I have had to revert the change as it stopped my site being usable.

    Thanks in advance

    bug 
    opened by docapotamus 13
  • Problem with importing wtforms inside html5.py file

    Problem with importing wtforms inside html5.py file

    I'm doing blog application to learn Python and Flask and I would like to launch it on Google App Engine. Unfortunately I have small problem with importing WTForms to the application. I'm currently using Flask 0.9, WTForms 1.0.1 and Flask-WTForms 0.8. I've added flaskext_wtf folder to root path of my project but I'm getting error from html5.py file.

    [code] File "/Users/lucas/Workspace/blog/flask_wtf/html5.py", line 1, in from wtforms import TextField File "/Users/lucas/Workspace/blog/flask/exthook.py", line 86, in load_module raise ImportError('No module named %s' % fullname) ImportError: No module named flask.ext.wtf.wtforms It looks like it tries to find wtforms inside the extension path instead of my project path. How can I inform the html5.py file to look for the wtforms in the root?[/code]

    Here are sources of my project - https://bitbucket.org/lucas_mendelowski/wblog/src

    opened by lcmen 13
  • Recaptcha validator passes Google the wrong IP

    Recaptcha validator passes Google the wrong IP

    This part of the validation code https://github.com/lepture/flask-wtf/blob/0598f96f70a695d5f84c05a9f4e11feff1d64caa/flask_wtf/recaptcha/validators.py#L43

    It's sending Google servers the wrong IP when the application is being proxied by something like nginx. Replacing request.remote_addr with request.access_route[-1] should fix the issue when being proxied.

    opened by Avamander 11
  • How to use the built-in translations provided by WTForms

    How to use the built-in translations provided by WTForms

    As describe in WTForms's documentation here, we can define a base class to set the default locale app-widely:

    from wtforms import Form
    
    class MyBaseForm(Form):
        class Meta:
            locales = ['es_ES', 'es']
    

    How to achieve this with Flask-WTF?

    opened by greyli 10
  • Why use referrer header for CSRF protection when you have sychronizer tokens?

    Why use referrer header for CSRF protection when you have sychronizer tokens?

    I'm new to the security game. I'd understood that a sychronizer token and a referrer header were doing basically the same thing, and that a sychronizer token is more robust. What does a referrer header add that a sychronizer token doesn't address?

    csrf 
    opened by knod 9
  • Fix forms & csrf_enabled deprecation doc

    Fix forms & csrf_enabled deprecation doc

    I had hard times understanding the deprecation of csrf_enabled. The only way I managed to do it was by reading form.py.

    Let's make the doc and deprecation message better :-)

    opened by JocelynDelalande 9
  • TypeError: b'' is not JSON serializable

    TypeError: b'' is not JSON serializable

    While using python 3.5.2 I got this error: TypeError: b'' is not JSON serializable So there is a problem with serializing a byte string For me I solved it this way editing csrf.py generate_csrf method: setattr(g, field_name, s.dumps(session[field_name].decode('utf-8'))) I added .decode('utf-8') to session[field_name] to make it work on python 3.

    I am not sure if this is an issue, but may be I helped somehow :)

    opened by yerassyl 9
  • Forms should distinguish which one was submitted

    Forms should distinguish which one was submitted

    I have a page with two forms, one contains two checkboxes and the other some text inputs. I construct each form with data from DB, e.g. the checkboxes are sometimes preselected. When I submit the other form, then the form with the checkboxes thinks that it has been submitted too (the form.is_submitted() only looks at request and checks that its post or put). Therefore both checkboxes are set unchecked, as the form thinks that it has been submitted, but no data for the checkboxes are found (=> which means that the checkboxes get prefilled with False).

    invalid 
    opened by bkabrda 9
  • Disabling CSRF check by default doesn't work for forms

    Disabling CSRF check by default doesn't work for forms

    I noticed that setting WTF_CSRF_CHECK_DEFAULT doesn't won't work if the endpoint validates any FlaskForm. The CSRF token doesn't seem to be checked, but when I check the my logs, they say that The CSRF token is missing. Would it be possible to completely disable the CSRF check for forms if WTF_CSRF_CHECK_DEFAULT is set to false?

    opened by james9909 8
  • Add csrf_token() to Jinja2 globals

    Add csrf_token() to Jinja2 globals

    Installing csrf_token() in the render context only causes errors in imported Jinja2 templates. It can be avoided by explicitly importing templates with context, but it is a cognitive burden to remember which templates should be imported with context and which don't have to be.

    todo 
    opened by clee704 8
  • Missing/Inconsistent imports

    Missing/Inconsistent imports

    Since this project imports "everything" from WTForms, it should import everything, not just some of the things. Or better drop importing anything and let the user decide. With the current design you need to update the imports every time something changes in WTForm. That makes this project hard to maintain.

    As an example: In the init.py file you import SQL Alchemy ext (if its installed), but you don't import everything from this extension. SQL Alchemy validators.py are missing. This leaves the us with a situation were we have to guess what is imported by the flask-wtf ext and what has to be imported directly from WTForms.

    I know this design decision is not made by the current project maintainer, but it should be re-evaluated to find a better solution.

    opened by simonklee 8
  • Setting WTF_CSRF_TIME_LIMIT to

    Setting WTF_CSRF_TIME_LIMIT to "None" is confusing

    In #258, it is made "clear" that WTF_CSRF_TIME_LIMIT can be set to None. But this isn't entirely clear because what is None in the context of an environment variable?

    Is it the absence of a value (presumably not, because then we get the default of 3600 seconds) - ?

    Is it an empty string? I think a better value for the behavior of "limited by user session" would be 0. This works better with configuration by environment variable.

    opened by malthe 0
  • Set JSONEncoder to json._default

    Set JSONEncoder to json._default

    • fixes #528

    Checklist:

    • [ ] Add tests that demonstrate the correct behavior of the change. Tests should fail without the change.
    • [ ] Add or update relevant docs, in the docs folder and in code.
    • [ ] Add an entry in docs/changes.rst summarizing the change and linking to the issue. Add .. versionchanged:: entries in any relevant code docs.
    opened by pythops 1
  • AttributeError: module 'quart.json' has no attribute 'JSONEncoder'

    AttributeError: module 'quart.json' has no attribute 'JSONEncoder'

    Bump into this error when I run pipenv run hypercorn --reload --quic-bind 0.0.0.0:4433 --certfile server.crt --keyfile server.key --bind 0.0.0.0:8080 src.main:app:

    <snip>
      File "/usr/src/PythonRestAPI/src/main.py", line 5, in <module>
        from flask_wtf.csrf import CSRFProtect, CSRFError
      File "/home/khteh/.local/share/virtualenvs/PythonRestAPI-JI5RzKtM/lib/python3.10/site-packages/flask_wtf/__init__.py", line 4, in <module>
        from .recaptcha import Recaptcha
      File "/home/khteh/.local/share/virtualenvs/PythonRestAPI-JI5RzKtM/lib/python3.10/site-packages/flask_wtf/recaptcha/__init__.py", line 1, in <module>
        from .fields import RecaptchaField
      File "/home/khteh/.local/share/virtualenvs/PythonRestAPI-JI5RzKtM/lib/python3.10/site-packages/flask_wtf/recaptcha/fields.py", line 3, in <module>
        from . import widgets
      File "/home/khteh/.local/share/virtualenvs/PythonRestAPI-JI5RzKtM/lib/python3.10/site-packages/flask_wtf/recaptcha/widgets.py", line 6, in <module>
        JSONEncoder = json.JSONEncoder
    AttributeError: module 'quart.json' has no attribute 'JSONEncoder'
    

    Environment:

    • Python version: 3.10.4
    • Flask-WTF version: 1.0.1
    • Flask version: 2.1.3 https://github.com/pallets/quart/issues/163
    opened by khteh 2
  • Validate the MIME type of files using FileAllowed

    Validate the MIME type of files using FileAllowed

    The flask_wtf.file.FileAllowed validator is very useful to validate the extension of an uploaded file, however, it is also important to validate the MIME type of the files as a user could easily change the extension of a file to violate this validator, thus breaking the integrity of the application. This is also a recommendation made by the HTML Standard:

    Authors are encouraged to specify both any MIME types and any corresponding extensions when looking for data in a specific format.

    In my opinion, the best place to specify the allowed MIME types is in the same list that receives this validator (just as the accept attribute of <input type="file"> works), for example:

    FileAllowed(upload_set=["doc", "docx", "xml", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"])
    
    opened by Tedpac 1
  • 'REMEMBER_COOKIE_HTTPONLY' causes

    'REMEMBER_COOKIE_HTTPONLY' causes "The CSRF tokens do not match" on mobile Firefox

    I've noticed that when enabling 'REMEMBER_COOKIE_HTTPONLY' within the config dict, it causes "The CSRF tokens do not match" in a POST request specifically for mobile Firefox. Non-mobile works just fine, as does Chromium.

    1. Set 'REMEMBER_COOKIE_HTTPONLY' within the config dict
    2. Go to a page that has a CSRF token and do a post request
    3. It fails with a "The CSRF tokens do not match"

    The POST request should complete just fine

    Environment:

    • Python version: 3.8.10
    • Flask-WTF version: 1.0.1
    • Flask version: 2.1.2
    opened by Lvl4Sword 0
  • The CSRF session token is missing.

    The CSRF session token is missing.

    Actual Behavior

    Everything works fine when the user is logged in, 400 Bad Request happens when I try to log the user in... same behavior is when I try to register a user (csrf_token is missing in the session when the user is anonymous)... have I missed something to configure maybe?

    Note: We are not using the wtforms, we have our own custom scheme.

    Thanks!

    Environment

    • Python version: Python 3.9.12
    • wtforms version: Flask-WTF==1.0.1
    • Flask version: Flask==2.0.3
    opened by TomeCirun 9
Releases(v1.0.1)
A platform independent django form serializer

django-remote-forms A package that allows you to serialize django forms, including fields and widgets into Python dictionary for easy conversion into

WiserTogether, Inc. 219 Sep 20, 2022
A set of high-level abstractions for Django forms

django-formtools Django's "formtools" is a set of high-level abstractions for Django forms. Currently for form previews and multi-step forms. This cod

Jazzband 619 Dec 23, 2022
Automate your google form here!

Google Form Filler (GFF) - Automate your google form here! About The idea of this project came from my online lectures as one of my professors takes a

Jay Thorat 13 Jan 05, 2023
Bootstrap 3 integration with Django.

django-bootstrap3 Bootstrap 3 integration for Django. Goal The goal of this project is to seamlessly blend Django and Bootstrap 3. Want to use Bootstr

Zostera B.V. 2.3k Dec 24, 2022
A CBV to handle multiple forms in one view

django-shapeshifter A common problem in Django is how to have a view, especially a class-based view that can display and process multiple forms at onc

Kenneth Love 167 Nov 26, 2022
The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

4.6k Dec 31, 2022
Bootstrap 4 integration with Django.

django-bootstrap 4 Bootstrap 4 integration for Django. Goal The goal of this project is to seamlessly blend Django and Bootstrap 4. Requirements Pytho

Zostera B.V. 979 Dec 26, 2022
The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

4.6k Jan 05, 2023
A flexible forms validation and rendering library for Python.

WTForms WTForms is a flexible forms validation and rendering library for Python web development. It can work with whatever web framework and template

WTForms 1.4k Dec 31, 2022
Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.

django-widget-tweaks Tweak the form field rendering in templates, not in python-level form definitions. Altering CSS classes and HTML attributes is su

Jazzband 1.8k Jan 06, 2023
A fresh approach to autocomplete implementations, specially for Django. Status: v3 stable, 2.x.x stable, 1.x.x deprecated. Please DO regularely ping us with your link at #yourlabs IRC channel

Features Python 2.7, 3.4, Django 2.0+ support (Django 1.11 (LTS), is supported until django-autocomplete-light-3.2.10), Django (multiple) choice suppo

YourLabs 1.7k Jan 01, 2023
A Python HTML form library.

Deform Introduction Use cases Installation Example Status Projects using Deform Community and links Introduction Deform is a Python form library for g

Pylons Project 391 Jan 03, 2023
Streaming parser for multipart/form-data written in Python

Streaming multipart/form-data parser streaming_form_data provides a Python parser for parsing multipart/form-data input chunks (the encoding used when

Siddhant Goel 112 Dec 29, 2022
Simple integration of Flask and WTForms, including CSRF, file upload and Recaptcha integration.

Flask-WTF Simple integration of Flask and WTForms, including CSRF, file upload, and reCAPTCHA. Links Documentation: https://flask-wtf.readthedocs.io/

WTForms 1.3k Jan 04, 2023
Simple integration of Flask and WTForms, including CSRF, file upload and Recaptcha integration.

Flask-WTF Simple integration of Flask and WTForms, including CSRF, file upload, and reCAPTCHA. Links Documentation: https://flask-wtf.readthedocs.io/

WTForms 1.3k Jan 04, 2023
FlaskBB is a Forum Software written in Python using the micro framework Flask.

FlaskBB is a Forum Software written in Python using the micro framework Flask.

FlaskBB 2.3k Dec 30, 2022
Easy and free contact form on your HTML page. No backend or JS required.

Easy and free contact form on your HTML page. No backend or JS required. 🚀 💬

0xDEADF00D 8 Dec 16, 2022
Full control of form rendering in the templates.

django-floppyforms Full control of form rendering in the templates. Authors: Gregor Müllegger and many many contributors Original creator: Bruno Renié

Jazzband 811 Dec 01, 2022