Search code examples
pythonmongoengineflask-mongoengine

Mongoengine custom validation with modify


I am trying to apply custom validation on a Mongoengine modify operation as seen below:

class Form(Document):

    fields = ListField(EmbeddedDocumentField(Field))

    def modify(self, *args, **kwargs):
        for field in self.fields:
            if not [field for field in self.fields if field.type == "email"]:
                raise ValidationError("Form must have an email field")

        super(Form, self).modify(**kwargs)

     def update_form(self, modify_kwargs):
         return self.modify(**modify_kwargs)

However when I call update_form, the custom validation does not take the updated data into account in modify. Is there some sort of a pre-hook for doing this type of validation?


Solution

  • You're verifying against the objects field attribute rather than kwargs. But make sure each field is an object that contains .type. You shouldn't be using the python reserved word type though.

    class Form(Document):
    
    fields = ListField(EmbeddedDocumentField(Field))
    
    def modify(self, *args, **kwargs):
         if not [field for field in kwargs.get('fields', []) if field.type == "email"]:
             raise ValidationError("Form must have an email field")
    
        super(Form, self).modify(**kwargs)
    
     def update_form(self, modify_kwargs):
         return self.modify(**modify_kwargs)