MongoEngine flask extension with WTF model forms support



Info: MongoEngine for Flask web applications.


Flask-MongoEngine is a Flask extension that provides integration with MongoEngine. It handles connection management for your app. You can also use WTForms as model forms for your models.


You can find the documentation at


You can install this package using pypi: pip install flask-mongoengine


To run the test suite, ensure you are running a local copy of Flask-MongoEngine and simply run: pytest.

To run the test suite on every supported versions of Python, PyPy and MongoEngine you can use tox. Ensure tox and each supported Python, PyPy versions are installed in your environment:

# Install tox
$ pip install tox
# Run the test suites
$ tox

To run a single or selected test suits, use pytest -k option.


We welcome contributions! see the Contribution guidelines



Flask-MongoEngine is distributed under MIT license, see LICENSE for more details.

  • Next Milestone Questions & Call for Maintainers!

    Next Milestone Questions & Call for Maintainers!

    @anemitz & @thomasst do you guys have any plans for the next milestone / release of flask-mongoengine?

    Unfortunately, I dont have the time available at the minute to fix the issues and push a release. If you are in the same boat, I'm happy to try and draft in more maintainers!

    Any potential maintainers - please post here if you want to help further flask-mongoengine - I'm happy to mentor as well!

    opened by rozza 50
  • add mongomock if app.config['TESTING']

    add mongomock if app.config['TESTING']

    i would love to be able to have a mongomock connection if app.config['TESTING'] is true this would allow easier testing of the flask application (otherwise an in-memory mongo like the one implemented in ming would be great)

    type: enhancement 
    opened by ocean1 18
  • Can't install flask-mongoengine in my virtual environment

    Can't install flask-mongoengine in my virtual environment

    pip install flask-mongoengine Collecting flask-mongoengine Using cached flask-mongoengine-0.9.5.tar.gz (111 kB) ERROR: Command errored out with exit status 1: command: 'c:\users\keerthivasan\desktop\pybox\venv\scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\keerthivasan\AppData\Local

    \Temp\pip-install-su4c26f2\flask-mongoengine\'"'"'; file='"'"'C:\User s\keerthivasan\AppData\Local\Temp\pip-install-su4c26f2\flask-mongoengine\setup. py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);'"'" '\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg _info --egg-base 'C:\Users\keerthivasan\AppData\Local\Temp\pip-pip-egg-info-xw613uem' cwd: C:\Users\keerthivasan\AppData\Local\Temp\pip-install-su4c26f2\flask-mong oengine\

    im trying to install flask-mongoengine but can't for some reasons. Help me out

    opened by keerthivasan-g 18
  • PyPi package is outdated.

    PyPi package is outdated.

    Hello, I think that the PyPI package needs to be updated. The stable branch contains changes since it was last uploaded (about year ago).


    opened by icoz 17
  • Using mongodb:// style uri's no longer work

    Using mongodb:// style uri's no longer work

    This line is the culprit. Was noticed before the release of 0.8 :(

    I get a failure: pymongo.errors.ServerSelectionTimeoutError: r2d2_local:27017: [Errno -2] Name or service not known

    r2d2_local is the name of my database, not my host.

    type: bug 
    opened by agani 16
  • Document and fix connection code

    Document and fix connection code

    Reverting/ fixing changes from Relevant criticism:

    The main goal of this PR is to fix a buggy connection code introduced in v0.8. It also makes the code cleaner and easier to understand through a better separation of responsibilities and a better documentation.

    This is unfortunately dropping support for mongomock, but many things were broken about it to begin with. We should revisit adding it in the future, though personally I don't see a point for it... In the age of Travis/CircleCI/etc., it's so easy to run a real MongoDB in your tests.

    Things to test manually:

    • [x] Connecting to multiple mongos in a sharded cluster
    • [x] Connecting to a replica set
    • [x] Connecting to a server that requires authentication
    • [x] All of the above via a MongoDB URI

    Fixes #266 #283 #282 #259 #258 #254 #250 #247 #267

    opened by wojcikstefan 12
  • model_form Forms return '' instead of None for empty fields.

    model_form Forms return '' instead of None for empty fields.

    The email field validates '' differently than None. '' is an invalid email, None is a valid input. model_form based Forms return the wrong data.

    from flask import Flask
    from flask.ext.mongoengine import MongoEngine
    import unittest
    from import model_form
    from werkzeug.datastructures import MultiDict
    app = Flask(__name__)
        DEBUG = True,
        TESTING = True,
        MONGODB_HOST = 'localhost',
        MONGODB_PORT = '27017',
        MONGODB_DB = 'mongorest_example_app',
    db = MongoEngine(app)
    class User(db.Document):
        email = db.EmailField(required=False)
        name = db.StringField()
    class FieldTestCase(unittest.TestCase):
        def setUp(self):
   = app.test_client()
        def test_emptyemail(self):
            with app.test_request_context('/?name=Peter'):
                TestForm = model_form(User)
                data = MultiDict({'name':'John Doe'})
                form = TestForm(data,csrf_enabled=False)
                assert form.validate()
                assert['email'] == None
    #['email'] is '' instaed of None
    opened by lucasvo 12
  • while assigning replicaSet parameter, the replicaSet is gone. This is because of the below code...

    while assigning replicaSet parameter, the replicaSet is gone. This is because of the below code...

    In master branch, flask_mongoengine/, line 265:

    if conn_setting.pop('replicaset', None):
        resolved['replicaSet'] = conn_setting.pop('replicaset', None)

    what is f***ing going on lol

    Because dict.pop() will return and also remove specific key value pair from dict, so we cannot do dict.pop() twice. Actually this code should be:

    replica_set = conn_setting.pop('replicaset', None)
    if replica_set:
        resolved['replicaSet'] = replica_set
    type: bug 
    opened by fieliapm 11
  • Model form generator now accepts wtf custom 'validators' and 'filters' on model field definition.

    Model form generator now accepts wtf custom 'validators' and 'filters' on model field definition.

    Added a wrapper sub-class WtfBaseField to allow additional WTForm field parameters and settings needed by flask-mongoengine, without necessarily going through to the core mongoengine BaseField.

    • flask_mongoengine/ has patching to redirect wtf mongoengine Fields of base BaseField to use WtfBaseField
    • wtf/ now has 'validators' and 'filters' allowed on behalf wtf model field generator.


     class Contact(db.Document)
        telephone = db.StringField(
              validators.InputRequired(message=u'Missing telephone.'),
    opened by losintikfos 11
  • Not working select by ObjectId

    Not working select by ObjectId

    Not working those code:

    class Currency(db.Document):
        title = db.StringField(max_length=40, min_length=3)
    class ExchangeRate(db.Document):
        in_currency = db.ReferenceField(Currency)
        out_currency = db.ReferenceField(Currency)

    in result empty list in_currency - ObjectId string like '5188a1deb071b651323d7e89' few days before all worked ok mongoengine 0.8RC2 can`t downgrade by pip for testing flask-mongoenigne latest from github

    opened by oleksandr-l5 10
  • Encode DBRef and ObjectId

    Encode DBRef and ObjectId


    opened by idoshr 0
  • Add domain, path, secure, samesite options to session interface

    Add domain, path, secure, samesite options to session interface

    opened by Fethbita 0
  • MongoEngineSessionInterface doesn't support SAMESITE attribute

    MongoEngineSessionInterface doesn't support SAMESITE attribute

    The SameSite attribute is ignored when flask-mongoengine session interface is used. See save_session in flask-mongoengine and flask:

    opened by Fethbita 0
  • check_keys support

    check_keys support is not support check_keys argument, but mongoengine support. How can i pass check_keys to mongoengne .insert()?

    opened by zloyded 0
  • [CLOSES 408] basequeryset get or 404 incorrectly handles message

    [CLOSES 408] basequeryset get or 404 incorrectly handles message

    I am not sure if same parameter should be added to frist_or_404 just for consistency. It will probably break some current projects

    opened by devsagul 0
  • Omit CSRF token when populating model instance with form data (Fix #436)

    Omit CSRF token when populating model instance with form data (Fix #436)

    Fix #436

    When no model instance was provided to ModelForm, creates the model instance itself.

    Preivously, the instance was initialized with values from which contains all form fields. This causes an error with e.g. CSRF-protected forms, because an auxiliary parameter such as csrf_token is expected to be a field declared on the model. (The problem is also described here.)

    With this PR, the field values are passed via Form.populate_obj() instead of, as the method respects field-specific rules, i.e. omits CSRFTokenFields.

    opened by numirias 0
  • FieldDoesNotExist error when saving WTForms model form submitted with CSRF token

    FieldDoesNotExist error when saving WTForms model form submitted with CSRF token


    When saving a WTForms model form that includes a CSRF token, the token is added as a field value to the model instance. E.g.:

    class MyModel(db.Document):
    MyForm = model_form(MyModel)
    form = MyForm(request.POST)

    With CSRF protection enabled, this raises an exception such as:

    mongoengine.errors.FieldDoesNotExist: The fields "{'csrf_token'}" do not exist on the document "MyModel"

    Expected behavior

    When saving the form submission, the CSRF token gets omitted, as it's not a declared field on the model.

    opened by numirias 0
  • config bug resolved

    config bug resolved

    When we pass config dict directly to MongoEngine constructor and pass config=None in init_app function and no mongoengine settings in app.config , we need to pass self.config to create_connections function

    opened by srinivas365 0
  • Rewrite connection module

    Rewrite connection module

    I had a time to look at connection module, that originally was made in 2016-2017. In nearest past there was a lot of question and bugs related to connection. By my opinion our old connection module did a lot of work, that should not be done in this package at all. For example there is some things that by my opinion is not correct:

    • Setting of some connection defaults - we should not do it, as same defaults will be set in upstream mongoengine/pymongo packages. We do not do anything with these defaults, but do the work that hard to track. Also as it is hard to track changes in parent packages, that should be implemented here.
    • Replacing mongomock urls - in this package mongomock support was dropped in version 0.8.1, but mongomock settings handled by mongoengine upstream package. We should not try to do the work, that is done in package with much more contributtors.
    • Different behavior on dict or list settings - old implementation had two types in return of connection functions. In case one db used it was dict, in case of multiple dbs it was list. It is not correct and can be considered as unexpected behavior.

    So at the end this Pull request will:

    • Removed unexpected set of defaults. User is now fully responsible to set correct defaults, or defaults from upstream mongoengine and pymongo will be used.
    • Connection property of flask-mongoengine MongoEngine class now will always return dict with one or many database connections.
    • Connection handling now the same for one connection or many connections. Before this PR it was difference when 1 or many DB used.
    • Updated tests for new behavior.

    TODO before merge:

    • Documentation update

    Should fix:

    • #385
    • #381
    • #386
    • Probably #420

    I honestly hope for any comments, and for some test users, as it is deep flask-mongoengine behavior change. Code reviews are welcomed on any stage.

    type: enhancement type: breaking-change log:breaking-change log:fixed stage: WIP 
    opened by insspb 0
  • v1.0.0(Nov 21, 2020)


    • Use fldt.$ to avoid double jQuery.noConflict(true) (#313) @martinhanzik
    • Run Travis builds in a container-based environment (#301) @wojcikstefan
    • Fix test and mongomock (#304) @touilleMan
    • Connect parameter (#321) @noirbizarre

    Breaking Changes

    • Update install requirements to last flask dependencies (#390) @insspb
    • Pymongo support < 3.6.0 dropped (#372) @insspb
    • Drop python versions from python 2.7 to 3.5 (#359) @insspb
    • Code reformatting, cleanup and formatting automation (#368) @insspb


    • Restored changelogs for versions 0.9.2-0.9.5 (#370) @insspb
    • Python 3.9 support added (#415) @insspb
    • Github workflows for labels verification and releases notes (#391) @insspb
    • Github Actions CI/CD tests for project (#394) @insspb
    • Added label_modifier option on ReferenceField conversion (#348) @sebbekarlsson
    • Add custom message option for get_or_404 function (#361) @insspb
    • Add DateField support #405 @qisoster (#416) @insspb
    • Add Codeclimate and codecov to Github CI/CD (#396) @insspb


    • Travis updated to use focal ubuntu images (#419) @insspb
    • Сlarify new URI style setting proccesing regarding db. (#329) @Irisha
    • Update Remove setup_requirements (#380) @9nix00
    • Update installation documentation (#378) @onlinejudge95
    • Tests refactoring. Moving to pytest engine (#397) @insspb
    • Replace general Exception raising with more detailed type (#398) @insspb
    • Remove six dependency (Drop Python 2.7 compatibility) (#393) @insspb
    • Changed: Imports order, drop imports for python 2.7 (#374) @insspb
    • Allow keep config in MongoEngine object until init_app (#401) @insspb


    • Pass 'places' to 'precision' in wtfForms DecimalField convertation (#343) @PeterKharchenko
    • ListField documentation extended with min_entries info (#353) @molitoris
    • Fixed: docstrings typo in flask_mongoengine/ (#383) @timgates42
    • Fix formdata default value on ModelForm <-> FlaskForm inheritance. (#387) @sdayu

    This release is made by wonderful contributors:

    @9nix00, @Irisha, @PeterKharchenko, @alysivji, @insspb, @itsnauman, @martinhanzik, @molitoris, @noirbizarre, @onlinejudge95, @qisoster, @sdayu, @sebbekarlsson, @timgates42, @touilleMan and @wojcikstefan

    Source code(tar.gz)
    Source code(zip)
  • v0.9.2(Feb 16, 2017)

  • v0.9.1(Feb 16, 2017)

    • Fixed for various platforms (#298).
    • Added Flask-WTF v0.14 support (#294).
    • MongoEngine instance now holds a reference to a particular Flask app it was initialized with (#261).
    Source code(tar.gz)
    Source code(zip)
  • v0.9.0(Dec 12, 2016)

  • v0.8.2(Dec 11, 2016)

  • 0.8.1(Nov 30, 2016)

  • 0.8(Aug 11, 2016)

    • Dropped MongoEngine 0.7 support
    • Added MongoEngine 0.10 support
    • Added PyMongo 3 support
    • Added Python3 support up to 3.5
    • Allowed empying value list in SelectMultipleField
    • Fixed paginator issues
    • Use InputRequired validator to allow 0 in required field
    • Made help_text Field attribute optional
    • Added "radio" form_arg to convert field into RadioField
    • Added "textarea" form_arg to force conversion into TextAreaField
    • Added field parameters (validators, filters...)
    • Fixed 'False' connection settings ignored
    • Fixed bug to allow multiple instances of extension
    • Added MongoEngineSessionInterface support for PyMongo's tz_aware option
    • Support arbitrary primary key fields (not "id")
    • Configurable httponly flag for MongoEngineSessionInterface
    • Various bugfixes, code cleanup and documentation improvements
    • Move from deprecated flask.ext.* to flask_* syntax in imports
    • Added independent connection handler for FlaskMongoEngine
    • All MongoEngine connection calls are proxied via FlaskMongoEngine connection handler
    • Added backward compatibility for settings key names
    • Added support for MongoMock and temporary test DB
    • Fixed issue with multiple DB support
    • Various other bugfixes
    Source code(tar.gz)
    Source code(zip)
  • 0.7.5(Jan 9, 2016)

    • Changes to resolve MongoEngine deprecated help_text and safe attribute issues.
    • Minor PyPy3 compatibility issue with operation tracker resolved.
    • SESSION_TTL setting is accepted via app config to set and override session timeout default.
    • Provided RadioField component via model form.
    • Other enhancements
    Source code(tar.gz)
    Source code(zip)
A curated list of awesome tools for SQLAlchemy

Awesome SQLAlchemy A curated list of awesome extra libraries and resources for SQLAlchemy. Inspired by awesome-python. (See also other awesome lists!)

Hong Minhee (洪 民憙) 2.3k Oct 21, 2021
Adds SQLAlchemy support to Flask

Flask-SQLAlchemy Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. It aims to simplify using SQLAlchemy

The Pallets Projects 3.6k Oct 22, 2021
a small, expressive orm -- supports postgresql, mysql and sqlite

peewee Peewee is a simple and small ORM. It has few (but expressive) concepts, making it easy to learn and intuitive to use. a small, expressive ORM p

Charles Leifer 8.7k Oct 25, 2021
Rich Python data types for Redis

Created by Stephen McDonald Introduction HOT Redis is a wrapper library for the redis-py client. Rather than calling the Redis commands directly from

Stephen McDonald 273 Sep 2, 2021
The Orator ORM provides a simple yet beautiful ActiveRecord implementation.

Orator The Orator ORM provides a simple yet beautiful ActiveRecord implementation. It is inspired by the database part of the Laravel framework, but l

Sébastien Eustace 1.3k Oct 17, 2021
The ormar package is an async mini ORM for Python, with support for Postgres, MySQL, and SQLite.

python async mini orm with fastapi in mind and pydantic validation

null 674 Oct 23, 2021
SQLModel is a library for interacting with SQL databases from Python code, with Python objects.

SQLModel is a library for interacting with SQL databases from Python code, with Python objects. It is designed to be intuitive, easy to use, highly compatible, and robust.

Sebastián Ramírez 5.5k Oct 24, 2021
A Python Library for Simple Models and Containers Persisted in Redis

Redisco Python Containers and Simple Models for Redis Description Redisco allows you to store objects in Redis. It is inspired by the Ruby library Ohm

sebastien requiem 434 Oct 1, 2021
Pydantic model support for Django ORM

Pydantic model support for Django ORM

Jordan Eremieff 189 Oct 23, 2021
A pythonic interface to Amazon's DynamoDB

PynamoDB A Pythonic interface for Amazon's DynamoDB. DynamoDB is a great NoSQL service provided by Amazon, but the API is verbose. PynamoDB presents y

null 1.7k Oct 23, 2021
Pony Object Relational Mapper

Downloads Pony Object-Relational Mapper Pony is an advanced object-relational mapper. The most interesting feature of Pony is its ability to write que

null 2.7k Oct 15, 2021
Tortoise ORM is an easy-to-use asyncio ORM inspired by Django.

Tortoise ORM was build with relations in mind and admiration for the excellent and popular Django ORM. It's engraved in it's design that you are working not with just tables, you work with relational data.

Tortoise 2.4k Oct 20, 2021
An async ORM. 🗃

ORM The orm package is an async ORM for Python, with support for Postgres, MySQL, and SQLite. ORM is built with: SQLAlchemy core for query building. d

Encode 1.4k Oct 11, 2021
Piccolo - A fast, user friendly ORM and query builder which supports asyncio.

A fast, user friendly ORM and query builder which supports asyncio.

null 566 Oct 20, 2021
Easy-to-use data handling for SQL data stores with support for implicit table creation, bulk loading, and transactions.

dataset: databases for lazy people In short, dataset makes reading and writing data in databases as simple as reading and writing JSON files. Read the

Friedrich Lindenberg 4.1k Oct 18, 2021