Source

wtforms / wtforms / ext / mongoengine / models.py

#coding=utf-8
#Author: Marat Khabibullin <maratfm@gmail.com>
from wtforms.form import Form
from document_update import Document
from mongoengine.base import BaseDocument

class ModelForm(Form):
    model_class = None
    def __init__(self, *args, **kwargs):
        self.instance = kwargs['obj'] = kwargs.pop('instance', None) or \
                                        kwargs.get('obj', None)
        self.model_class = kwargs.pop('model_class', None) or \
                           self.model_class or \
                           self.instance and self.instance.__class__

        assert issubclass(self.model_class, BaseDocument), 'ModelForm model_class attribute must be subclass of BaseDocument'
        assert self.instance is None or isinstance(self.instance, self.model_class), 'ModelForm instance attribute must be instance of model_class'

        super(ModelForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        if self.instance:
            update = {}
            for name, field in self._fields.iteritems():
                try:
                    if getattr(self.instance, name) != field.data:
                        update['set__' + name] = field.data
                except AttributeError:
                    raise Exception('Model %s has not attr %s but form %s has' \
                                    % (type(self.instance),
                                      name,
                                      type(self)))
            if not update:
                # Nothing is changed
                return self.instance
            update['commit'] = commit
            self.instance.update(**update)
        else:
            self.instance = self.model_class(**self.data)
            if commit:
                self.instance.save()
        return self.instance