New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
frameless with check for defined fields #7
Comments
Hi @njordr - you could consider the data validation approach in this snippet here: http://mongoframes.com/snippets/data-validation. If you only want to check that fields have a value then the |
I can use validation also on frameless? If so, sorry for the question :( |
Sorry no you would need to mixin the validation stuff with Frameless e.g you might do something along the lines of: class ValidatedFrameless(Frameless)
# The form attribute should be assigned a WTForm class
_form = None
def save(self, *fields):
"""Validate the document before inserting/updating it"""
# If no form is defined then validation is skipped
if not self._form:
return self.upsert(*fields)
# Build the form data
if not fields:
fields = self.fields
data = {f: self[f] for f in fields if f in self}
# Build the form to validate our data with
form = self._form(FormData(data))
# Reduce the form fields to match the data being saved
for field in form:
if field.name not in data:
delattr(form, field.name)
# Validate the document
if not form.validate():
raise InvalidDocument(form.errors)
# Document is valid, save the changes :)
self.upsert(*fields) |
Another very simple approach would be to use event hooks to do this, for example: class MyFramelessClass(Frameless):
_required_fields = {'_id', 'other_field', ...}
@classmethod
def _on_insert(cls, sender, frames):
for frame in frames:
# Validate all required fields are present before we insert a document
for field in cls._required_fields:
assert getattr(frame, field), 'No value defined for: ' + field
MyFramelessClass.listen('insert', MyFramelessClass._on_insert)
|
Great, thanks! |
Hi.
I've created a frameless class as stated here: http://mongoframes.com/snippets/frameless and it works like a charm :)
What about to introduce a check for the defined fields?
Here is an example of my frameless class:
Is it possible to force the new class to fill-in at least the two defined fields (_id and test)?
Thanks,
Giovanni
The text was updated successfully, but these errors were encountered: