mongoengine / flask-mongoengine Goto Github PK
View Code? Open in Web Editor NEWMongoEngine flask extension with WTF model forms support
License: Other
MongoEngine flask extension with WTF model forms support
License: Other
I'm using the form generator to avoid creating forms and having redundant code.
I've got two suggestions that could be useful:
{{ form.submit }}
works when the class is declared in the usual way with a SubmitField
. I think the point of a form is to do a POST or PUT request but adding HTML manually to a template seems pretty lame. I think adding it would be much better.password
or pass
would be useful to say the least. For example:#Declaration in model
class User(Document):
#other fields
password = StringField(required=True, max_length=50)
#other fields
#Form
class UserForm():
#other fields
password = PasswordField("Password", [validators.Required()])
#other fields
submit = SubmitField("Send")
It's lackluster comparing it to the original WTForms package... they're key points, at least for me.
The default value of formdata in ModelForm constructor should be flask.ext.wtf.form._Auto. Thereby the ModelForm instance is automatically updated with the form data on a submit. See lepture/flask-wtf
Trying to get the debug toolbar panel work with Python 3.3 needs a couple of small code tweaks.
Many tests fail then though, but that might be more generally a problem with Python 3 and Flask-MongoEngine?
See arsgeografica/flask-mongoengine@bf9d237202a62f73c2a0ec90383e26bd40a13187 for my changes.
I have an IntField in my DynamicDocument that is being returned as an 'ObjectId' field.
If I query the field directly in mongo, I see:
{ "fid" : 10200331 }
However if I print the field using flask-mongoengine, I see a hash of the int value and if I print the type, I see:
<class 'bson.objectid.ObjectId'>
When it should be:
<type 'unicode'>.
My model is defined like this:
class Alert(db.DynamicDocument):
meta = {'collection': 'alerts'}
fid = db.IntField(required=True, unique=True)
def __init__(self, **kwargs):
kwargs['fid'] = kwargs['id']
kwargs.pop('id')
super(Alert, self).__init__(**kwargs)
I've got other integers that are being interpreted correctly, but this is not. Any idea what's going on?
You have mentioned in the documentation that only 3 types of Fields are yet to be addressed like Geo, Obj, etc. Is there a plan to incorporate Image fields and File fields to enable web developers to focus on the layout and allow flask-mongoengine to act as the end to end broker?
The following small testcase
from flask import Flask
from flask.ext import admin
from flask.ext.admin.contrib.mongoengine import ModelView
from flask.ext.mongoengine import MongoEngine
db = MongoEngine()
class TestDocument( db.Document ):
blob = db.BinaryField()
app = Flask( __name__ )
app.config[ 'SECRET_KEY' ] = '123456790'
app.config['MONGODB_SETTINGS'] = {'DB': 'testing'}
db.init_app( app )
adm = admin.Admin( app, 'TestCase' )
adm.add_view( ModelView( TestDocument ) )
if __name__ == '__main__':
app.run()
gives the error you see in the snapshot below (nothing changes if the field is not left empty)
In flask_mongoengine/wtf/models.py
. There is no explanation to why it does that.
The current behavior is broken, since calling instance.update(safe_update=False)
results in an error.
In flask_mongoengine/wtf/orm.py lines 229, 231
ps. sorry for my english
The same issue as reported here pallets-eco/flask-debugtoolbar#55
from flask import Flask
from mongoengine import *
from flask_debugtoolbar import DebugToolbarExtension
from flask_mongoengine import MongoEngine
db = MongoEngine()
app = Flask(__name__)
app.config['MONGODB_DB'] = 'test'
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
app.config['DEBUG_TB_PANELS'] = (
'flask.ext.debugtoolbar.panels.versions.VersionDebugPanel',
'flask.ext.debugtoolbar.panels.timer.TimerDebugPanel',
'flask.ext.debugtoolbar.panels.headers.HeaderDebugPanel',
'flask.ext.debugtoolbar.panels.request_vars.RequestVarsDebugPanel',
'flask.ext.debugtoolbar.panels.template.TemplateDebugPanel',
'flask.ext.debugtoolbar.panels.logger.LoggingPanel',
'flask_debugtoolbar.panels.profiler.ProfilerDebugPanel',
'flask.ext.mongoengine.panels.MongoDebugPanel',
)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
app.debug = True
db.init_app(app)
DebugToolbarExtension(app)
class Projection(db.Document):
sequence = StringField()
@app.route('/')
def testing():
Projection._get_collection().insert({'a':1234})
return ''
if __name__ == '__main__':
app.run()
I think it would be cleaner to enable configuration using a MongoDB URI, which can be parsed to fill in the required environment variables.
For example, storing a simple 1-variable URI in the environment
MONGODB_URI = 'mongodb://test:[email protected]/testdb'
Which is then parsed and used for the connection, if present.
Is there a design choice to not enable this feature, or is it something you'd consider a patch for?
accessing the sample app results in the following trace:
(fm)hideo flask-mongoengine git:(master) python example/simpleapp.py
* Running on http://0.0.0.0:4000/
* Restarting with reloader
Traceback (most recent call last):
File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/flask_debugtoolbar/__init__.py", line 101, in dispatch_request
return view_func(**req.view_args)
File "/home/matt/fm/flask-mongoengine/example/simpleapp.py", line 50, in index
Todo(title="Simple todo A", text="12345678910").save() # Insert
File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/mongoengine/document.py", line 199, in save
object_id = collection.save(doc, safe=safe, **write_options)
File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/pymongo/collection.py", line 241, in save
return self.insert(to_save, manipulate, safe, check_keys, **kwargs)
TypeError: _insert() takes at most 4 arguments (5 given)
I'm using pycharm on windows 7 64bit and I'm able to install other packages as I want to, except flask-mongoengine (through pypi.python.org/pypi repos).
Error returned quite much as yet I don't know how to solve it all. But I saw this at the end:
distutils.errors.DistutilsError: Setup script exited with error: Unable to find vcvarsall.bat
I've tested to manually install under my windows env (include reinstall setup-tools, easy_install and pip), and another try under Linux Mint. There's no luck neithe, with the same error.
Is there any problem with the package at the moment?
Thanks.
On orm.py ~line 41
change:
'description': '',
to
'description': field.help_text or '',
When
Traceback (most recent call last):
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask\app.py", line 170
1, in call
return self.wsgi_app(environ, start_response)
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask\app.py", line 168
9, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask\app.py", line 168
7, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask\app.py", line 136
0, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask\app.py", line 135
8, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask_debugtoolbar__in
it__.py", line 101, in dispatch_request
return view_func(*_req.view_args)
File "C:\Users\choffman\Desktop\configurator\application\views.py", line 7, in
index
users = Setting.objects.all()
File "C:\Users\choffman\Desktop\venv\lib\site-packages\mongoengine\queryset\ma
nager.py", line 37, in get
queryset = queryset_class(owner, owner._get_collection())
File "C:\Users\choffman\Desktop\venv\lib\site-packages\mongoengine\document.py
", line 157, in _get_collection
cls.ensure_indexes()
File "C:\Users\choffman\Desktop\venv\lib\site-packages\mongoengine\document.py
", line 544, in ensure_indexes
drop_dups=drop_dups, *_opts)
File "C:\Users\choffman\Desktop\venv\lib\site-packages\pymongo\collection.py",
line 916, in ensure_index
return self.create_index(key_or_list, cache_for, *_kwargs)
File "C:\Users\choffman\Desktop\venv\lib\site-packages\pymongo\collection.py",
line 823, in create_index
*_self._get_wc_override())
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask_mongoengine\opera
tion_tracker.py", line 67, in _insert
'size': response_sizes[-1],
IndexError: list index out of range
flask 0.10.1, python 2.7.5, mogoengine 0.8.3, mongoDB v2.4.5,
I'm trying to save User with schema
class User(Document):
email = StringField(required=True)
first_name = StringField(max_length=50)
last_name = StringField(max_length=50)
ross = User(email='[email protected]', first_name='Ross', last_name='Lawley').save()
and happen nothing, after save(),nothing is stored in the mongodb, db is empty
Currently,
ModelSelectFieldMultiple returns Error if field exists but has None value
This occur when creating a new item,
as the object has not been created on page load.
Is there a way to render form fields as HTML?
The methods from the WTForms docs don't seem to work.
e.g.
import flask
from flask.ext.mongoengine import MongoEngine
from flask_debugtoolbar import DebugToolbarExtension
app = flask.Flask(__name__)
app.config['SECRET_KEY'] = 'not so secret'
app.config['MONGODB_SETTINGS'] = {'DB': 'testing'}
app.config['DEBUG_TB_PANELS'] = ('flask.ext.mongoengine.panels.MongoDebugPanel',)
app.debug = True
db = MongoEngine()
db.init_app(app)
DebugToolbarExtension(app)
class TestModel(db.Document):
meta = {"collection": "test", "allow_inheritance": False}
name = db.StringField()
@app.route('/')
def index():
names = [item.name for item in TestModel.objects().all()]
return "<html><body>Query result: %s</body></html>" % ', '.join(names)
if __name__ == "__main__":
if not TestModel.objects:
TestModel(name="Alice").save()
TestModel(name="Bob").save()
app.run(host="0.0.0.0", port=5000)
Debug says "No queries recorded", however there was an empty {} query and it has returned some data
Lines 148, 149 in operation_tracker.py
seems unnecessary
if not query_son:
return result
Not sure if bug: I have trouble with customization of complex fields through model_form
field_args = {'myfield': {'label': 'Custom label'}}
works with db.StringField()
, but have no effect with db.ListField(db.StringField())
import flask
from flask.ext.mongoengine import MongoEngine
from flask.ext.mongoengine.wtf import model_form
from wtforms import widgets
app = flask.Flask(__name__)
app.config.from_object(__name__)
app.config['MONGODB_SETTINGS'] = {'DB': 'testing'}
app.config['SECRET_KEY'] = "foo"
app.debug = True
db = MongoEngine()
db.init_app(app)
class TestModel(db.Document):
text = db.StringField()
lst = db.ListField(db.StringField())
GenericForm = model_form(TestModel)
CustomForm = model_form(TestModel, field_args = {'text': {'label': 'Custom label', 'widget': widgets.TextInput()},
'lst': {'label': 'Custom label', 'widget': widgets.HiddenInput()}})
@app.route('/')
def index():
document = TestModel.objects().first()
generic_form = GenericForm(obj=document)
custom_form = CustomForm(obj=document)
return flask.render_template_string("""
Generic form: <br><br>
{{ generic_form.text.label }} {{ generic_form.text }} <br>
{{ generic_form.lst.label }} {{ generic_form.lst }}
<br><br>
Custom form: <br><br>
This one has custom label and widget: <br>
{{ custom_form.text.label }} {{ custom_form.text }} <br><br>
But this - same as generic <br>
{{ custom_form.lst.label }} {{ custom_form.lst }}
""", generic_form=generic_form, custom_form=custom_form)
if __name__ == "__main__":
TestModel.objects().delete()
TestModel(text="foo", lst=["bar"]).save()
app.run(host="0.0.0.0", port=4000)
Great example code, however maybe it's nice to show in the example how to get to the actual paginated items:
(view)
paginated_comments = post.paginate_field('comments', page, per_page=3)
(template)
{% for comment in paginated_comments.items %} ..
The fix described in #9 seems to break flask-admin.
More precisely, given the following test case
from flask import Flask
from flask.ext import admin
from flask.ext.admin.contrib.mongoengine import ModelView
from flask.ext.mongoengine import MongoEngine
db = MongoEngine()
class TestDocument( db.Document ):
email = db.EmailField( required = False )
app = Flask( __name__ )
app.config[ 'SECRET_KEY' ] = '123456790'
app.config['MONGODB_SETTINGS'] = {'DB': 'testing'}
db.init_app( app )
adm = admin.Admin( app, 'TestCase' )
adm.add_view( ModelView( TestDocument ) )
if __name__ == '__main__':
app.run()
If one tries to create a new record None
appears as the default value for the email
field – this is a first bug.
If a save is attempted a form validation error happens (since, of course, None
is not a valid email address):
In the case the field is first cleaned (leaving it empty) and then saved, a model validation happens – this is a second bug, given that if the forms validate, the model should also:
(observe that in the screenshot None
reappeared as the field value, even if it was empty before the save button was hit).
I am using flask-mongoengine extension and I have a User class like this:
class User(db.Document, UserMixin):
email = db.StringField(max_length=120, required=True, unique=True)
password_hash = db.StringField(max_length=80, required=True)
active = db.BooleanField()
fb_id = db.StringField(max_length=120, required=False)
def __init__(self, email, password, fb_id=None, active=True):
hashp = md5.md5(password).hexdigest()
self.email=email
self.password_hash=hashp
self.fb_id=fb_id
self.active=active
But when I do a simple get: User.objects.get(email = email)
I get the error:
TypeError: __init__() got an unexpected keyword argument 'password_hash'
but I am setting the password_hash in my init though. Surprisingly, if I delete the whole __init__
and pass in everything by args, it works fine.
So I recon I am doing something wrong in the __init__
, maybe something due the document super class? I am quite stuck on this, would appreciate your help.
This error occurs when MongoDebugPanel trying to build a stack trace and there are non-ascii comments in source code
# coding: utf-8
import flask
from flask.ext.mongoengine import MongoEngine
from flask.ext.debugtoolbar import DebugToolbarExtension
from mongoengine import StringField, ListField, Document
app = flask.Flask(__name__)
app.config.from_object(__name__)
app.config['MONGODB_SETTINGS'] = {'DB': 'testing'}
app.config['SECRET_KEY'] = "foo"
app.config['DEBUG_TB_PANELS'] = ('flask.ext.mongoengine.panels.MongoDebugPanel',)
app.debug = True
db = MongoEngine()
db.init_app(app)
DebugToolbarExtension(app)
class TestModel(Document):
text = StringField()
@app.route('/')
def index():
TestModel(text="foo").save() # ПЫЩЬ! - this comment triggers UnicodeDecodeError
return flask.render_template_string("<html><body></body></html>")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=4000)
So, we need something like this in operation_tracker.py:_tidy_stacktrace()
try:
text = ''.join(text).strip().decode('utf-8').strip()
except UnicodeDecodeError:
text = "[BAD UNICODE DATA] %s:%s" % (path, line_no)
# it would be better to display this as string-escape
# but I've lost with this unicode mess
This is probably related to #23. If the model contains a ListField
wrapping an EmbeddedDocumentField
and the latter is built from a string, then model_form
fails.
The following code shows the problem
from flask.ext.mongoengine import MongoEngine
from flask.ext.mongoengine.wtf import model_form
db = MongoEngine()
class EmbedMe( db.EmbeddedDocument ):
afield = db.StringField()
class Outer( db.Document ):
embedded = db.ListField( db.EmbeddedDocumentField( EmbedMe ) )
class OuterString( db.Document ):
embedded = db.ListField( db.EmbeddedDocumentField( 'EmbedMe' ) )
print model_form( Outer )
print model_form( OuterString )
I'm sure I can provide a failing test based on aa6f13c and the snippet above, but I'm not sure I can also provide a fix.
Dear @rozza, can you help?
1
class FFF(db.Document):
choices666 = ((1, 'choice1'), (2, 'choice2'))
d = ListField(IntField(choices=choices666))
FFForm = model_form(FFF)
File "C:/djang/flaskConvert/some.py", line 20, in <module>
FFForm = model_form(FFF)
File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 269, in model_form
field_dict = model_fields(model, only, exclude, field_args, converter)
File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 237, in model_fields
field = converter.convert(model, model_field, field_args.get(name))
File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 78, in convert
return self.converters[ftype](model, field, kwargs)
File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 158, in conv_List
return self.convert(model, field.field, **kwargs)
TypeError: convert() got an unexpected keyword argument 'multiple'
How I can resolve this error?
File "/usr/local/lib/python2.7/dist-packages/mongoengine/connection.py", line 95, in get_connection
raise ConnectionError(msg)
mongoengine.connection.ConnectionError: You have not defined a default connection
model.py:
from flask.ext.mongoengine import MongoEngine
db = MongoEngine()
class Currencies(db.Document):
# meta = {"db_alias": "currencies"}
name = db.StringField(max_length=40, min_length=3)
def __unicode__(self):
return self.name
mongo engine config in app.py:
from models import db
app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {'DB':'testing'}
db.init_app(app)
views.py:
from models import Currencies
print Currencies.objects.find()
Flask-Admin normally work
nm
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)
ExchangeRate.objects(in_currency=in_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
The model_form function does not accept models with field = EmbeddedDocumentField('StringInsteadOfModel')
. This is however supported by mongoengine itself.
It would be great if there was an option to allow users to enable some form of reaping of expired sessions. A suggested solution might be to reap if an expired session is encountered, this way reaping is seamless. The alternative is to provide a user callable method to perform a clean up.
Traceback (most recent call last):
File "C:/djang/flaskAPI/wsgi.py", line 10, in
from flask_mongoengine.wtf.orm import model_form
File "C:\Python27\lib\site-packages\flask_mongoengine__init__.py", line 9, in
from mongoengine.base import ValidationError
ImportError: cannot import name ValidationError
For example if you have a intfield with choices, it shows an error
Example code not working:
class PaymentSystem(db.Document):
title = db.StringField(min_length=3, max_length=40)
module_name = db.StringField(min_length=3, max_length=40)
comission_type = db.IntField(choices=COMMISSION_TYPES)
commission_value = db.FloatField(default=0.0)
config = db.StringField(max_length=1024)
def update(self, **kwargs):
print 'update', kwargs
def __unicode__(self):
return self.title
mongoengine 0.8.0RC4
flask-mongoengine 0.7.0RC1
maybe it not working because I change update with Flask-Admin
Document all settings / configuration
See: http://stackoverflow.com/questions/13942686/how-to-run-flask-and-mongoengine-with-a-remote-host
This repo seems more active, so let's try here. Original bug report: https://github.com/sbook/flask-mongoengine/issues/19
Traceback (most recent call last):
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/app.py", line 1518, in __call__
return self.wsgi_app(environ, start_response)
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/app.py", line 1506, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/app.py", line 1504, in wsgi_app
response = self.full_dispatch_request()
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/app.py", line 1264, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/app.py", line 1262, in full_dispatch_request
rv = self.dispatch_request()
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/app.py", line 1248, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/jonas/workspace/checklists/auth.py", line 58, in _decorate
return view(*args, **kwargs)
File "/home/jonas/workspace/checklists/app.py", line 70, in home
return render_template('home.html', templates=templates, checklists=checklists)
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/templating.py", line 123, in render_template
context, ctx.app)
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/templating.py", line 107, in _render
rv = template.render(context)
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/jinja2/environment.py", line 894, in render
return self.environment.handle_exception(exc_info, True)
File "/home/jonas/workspace/checklists/templates/home.html", line 1, in top-level template code
{% extends "base.html" %}
File "/home/jonas/workspace/checklists/templates/base.html", line 38, in top-level template code
{% block content %}
File "/home/jonas/workspace/checklists/templates/home.html", line 14, in block "content"
{% for template in templates %}
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/mongoengine/queryset.py", line 1494, in __iter__
self.rewind()
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/mongoengine/queryset.py", line 975, in rewind
self._cursor.rewind()
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/mongoengine/queryset.py", line 581, in _cursor
self._cursor_obj = self._collection.find(self._query,
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/mongoengine/queryset.py", line 555, in _collection
if self._collection_obj.name not in db.collection_names():
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/pymongo/database.py", line 363, in collection_names
names = [r["name"] for r in results]
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/pymongo/cursor.py", line 747, in next
if len(self.__data) or self._refresh():
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/pymongo/cursor.py", line 698, in _refresh
self.__uuid_subtype))
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/pymongo/cursor.py", line 657, in __send_message
self.__tz_aware)
File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/pymongo/helpers.py", line 102, in _unpack_response
error_object["$err"])
OperationFailure: database error: unauthorized db:mydb lock type:-1 client:84.226.127.220
I'm referencing an issue from MongoEgine, since it seems to be related to Flask: MongoEngine/mongoengine#205
Here is the original issue, I have the same problem with mongoengine==0.7.9:
I'm able to create multiple documents with the same values in the fields I've defined using unique_with. I'm using mongoengine in conjunction with flask-mongoengine in my flask app.
Here's my document definition:
class Item (db.Document):
owner_id = db.ObjectIdField(required=True)
owner_item_id = db.StringField(required=True, unique_with = 'owner_id')
Using the above document definition, I'm able to create multiple Items using the same owner_id and owner_item_id combination. The only time the NotUniqueError exception is thrown is the first time time I insert a duplicate document after I restart my local flask app. Every time after that, I can create as many duplicate documents as I wish.
Versions:
flask-mongoengine==0.6
mongoengine==0.7.8
@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!
class Channel(db.Document):
title = StringField()
form = model_form(Channel, only=['title'])
if form.validate_on_submit():
pass
return render_template('app.html', form=form)
in app.html
{{ form.errors }}
<form method='post'>
{{ form.csrf_token }}
{{ form.title }}
<input type="submit">
</form>
If i change the form to a normal flask_wtf Form it works!
class FFF(db.Document):
a = IntField()
b = StringField()
c = BooleanField()
FFForm = model_form(FFF, only=['b'])
FFForm = model_form(FFF, only=['b'])
File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 269, in model_form
field_dict = model_fields(model, only, exclude, field_args, converter)
File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 235, in model_fields
for name in field_names:
File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 230, in <genexpr>
field_names = (x for x in only if x in field_names)
ValueError: generator already executing
How I can resolve this error?
File "/usr/local/lib/python2.7/dist-packages/mongoengine/connection.py", line 95, in get_connection
raise ConnectionError(msg)
mongoengine.connection.ConnectionError: You have not defined a default connection
model.py:
from flask.ext.mongoengine import MongoEngine
db = MongoEngine()
class Currencies(db.Document):
# meta = {"db_alias": "currencies"}
name = db.StringField(max_length=40, min_length=3)
def __unicode__(self):
return self.name
mongo engine config in app.py:
from models import db
app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {'DB':'testing'}
db.init_app(app)
views.py:
from models import Currencies
print Currencies.objects.find()
Flask-Admin normally work
Should support all connection params detailed here:
http://api.mongodb.org/python/current/api/pymongo/connection.html
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 flask.ext.mongoengine.wtf import model_form
from werkzeug.datastructures import MultiDict
app = Flask(__name__)
app.config.update(
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):
self.app = 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 form.data['email'] == None
# form.data['email'] is '' instaed of None
I have the following inside a document class
tags = db.ListField(db.StringField(max_length=30, min_length=1), required=True)
I use the model_form to create the form.
If I send back a tag field with no content the form.validate() function should return False.
Instead, the function is returning True.
It is then left to Mongo to pick up the validation error and throw an exception.
ValidationError (Post:51ad4c74c47f3e07507984f4) (3.String value is too short: ['tags'])
The form.validate() function should validate the contents of ListField's.
It seems like the unique
flag in MongoEngine is not reflected properly in the WTForms validation. I have a model like this (where the email
is unique):
class User(database.Document):
""" User model """
email = database.EmailField(required=True, unique=True)
first_name = database.StringField(required=True, max_length=30)
last_name = database.StringField(required=True, max_length=30)
password = database.StringField(required=True)
is_active = database.BooleanField(default=False)
is_authenticated = database.BooleanField(default=False)
But when I save this I get a mongoengine.errors.NotUniqueError
from MongoEngine. I expected to get an error message from the form validation instead.
import flask
import datetime
from flask.ext.mongoengine import MongoEngine
from flask_debugtoolbar import DebugToolbarExtension
from mongoengine import *
from mongoengine.queryset import QuerySet
app = flask.Flask(__name__)
app.config['SECRET_KEY'] = 'not so secret'
app.config['DEBUG_TB_PANELS'] = ('flask.ext.mongoengine.panels.MongoDebugPanel',)
app.debug = True
db = MongoEngine()
db.init_app(app)
DebugToolbarExtension(app)
class AwesomerQuerySet(QuerySet):
pass
def filter_project(self, project_id):
gt = int(str(project_id)+"000000000000")
lt = int(str(project_id)+"999999999999")
return self.__call__(pk__gte=int(str(project_id)+"000000000000")).filter(pk__lte=int(str(project_id)+"999999999999"))
def filter_date(self,project_id,date,gt=False):
date_int = int(str(project_id)+str(int(time.mktime(date.timetuple()) * 100 + random.randrange(99))))
return self.__call__(pk__gt=date_int) if gt else self.__call__(pk__lt=date_int)
class PP(db.Document):
theid= SequenceField(primary_key=True)
class Parent(object):
updated = DateTimeField(db_field="2")
created = IntField(primary_key=True)
meta = {'cascade': False, 'allow_inheritance': False, 'queryset_class': AwesomerQuerySet}
@classmethod
def pre_save(cls, sender, document, **kwargs):
document.gen_pk()
print "pre_save"
def gen_pk(self):
self.created = str(self.project.pk)+str(int(time.mktime(datetime.datetime.utcnow().timetuple()) * 100 + random.randrange(99)))
class One(Parent,db.Document):
related_videos = ListField(ReferenceField('Video',dbref=False),db_field="r")
ssss = StringField()
title = StringField(db_field="t")
meta = {'cascade': False, 'allow_inheritance': False, 'queryset_class': AwesomerQuerySet}
signals.pre_save.connect(One.pre_save, sender=One)
@app.route('/test/')
def domain_testing():
pp = PP()
pp.save()
one = One(project=pp)
one.save()
return render_template("empty.html")
The problems:
Save is triggered twice on the One class.
There should be 3 queries in the toolbar:
1.PP created
2.One create
3.One updated.
Only 3 is in the toolbar. PP object is not saved in the db. Ignore the queryset.
I've noticed an ambiguous behavior of operation_tracker.py:_tidy_stacktrace() function: if your project located somewhere in "/var/www/html/myproject/", all queries will be marked as internal and hidden.
Probably here we must check file extension but not just "html" substring?
fname = sys._getframe(i).f_code.co_filename
if 'html' in fname:
fnames.append(fname)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.