Ejemplo n.º 1
0
    def get_form(self, Form=None):
        self.set_mongoadmin()
        context = self.set_permissions_in_context({})

        if not context['has_edit_permission']:
            return HttpResponseForbidden(
                "You do not have permissions to edit this content.")

        self.document_type = getattr(self.models, self.document_name)
        self.ident = self.kwargs.get('id')
        try:
            self.document = self.document_type.objects.get(pk=self.ident)
        except self.document_type.DoesNotExist:
            raise Http404
        if Form is None:
            Form = self.get_form_class()

        self.form = Form()

        if self.request.method == 'POST':
            self.form = self.process_post_form('Your changes have been saved.')
        else:
            self.form = MongoModelForm(model=self.document_type,
                                       instance=self.document).get_form()
        return self.form
Ejemplo n.º 2
0
 def test_form_fields_default_sort_ordering(self):
     # At default, the form fields will be ordered by python sorted()
     my_form = MongoModelForm(None, model=User,
                              instance=self.author).get_form()
     field_names = [field.name for field in my_form]
     self.assertEquals(field_names,
                       ['email', 'first_name', 'id', 'last_name'])
Ejemplo n.º 3
0
    def process_post_form(self, success_message=None):
        """
        As long as the form is set on the view this method will validate the form
        and save the submitted data.  Only call this if you are posting data.
        The given success_message will be used with the djanog messages framework
        if the posted data sucessfully submits.
        """

        # When on initial args are given we need to set the base document.
        if not hasattr(self, 'document') or self.document is None:
            self.document = self.document_type()
        form = self.form
        self.form = MongoModelForm(model=self.document_type, instance=self.document,
                                   form_post_data=self.request.POST).get_form()
        self.form.is_bound = True
        if self.form.is_valid():

            self.document_map_dict = MongoModelForm(model=self.document_type).create_document_dictionary(self.document_type)
            self.new_document = self.document_type

            # Used to keep track of embedded documents in lists.  Keyed by the list and the number of the
            # document.
            self.embedded_list_docs = {}

            if self.new_document is None:
                messages.error(self.request, u"Failed to save document")
            else:
                self.new_document = self.new_document()

                for form_key in self.form.cleaned_data.keys():
                    if form_key == 'id' and hasattr(self, 'document'):
                        self.new_document.id = self.document.id
                        continue
                    self.process_document(self.new_document, form_key, None)

                try:
                    self.new_document.save()
                except DocumentValidationError, e:
                    success_message = False

                    if e.errors:
                        error_fields = []

                        for field_name, error in e.errors.items():
                            self.form._errors[field_name] = self.form.error_class([error.message])
                            if field_name in self.form.cleaned_data:
                                error_fields.append(field_name)
                                del self.form.cleaned_data[field_name]
                        messages.error(self.request, u"Failed to save document%s" %
                                                     ' in ' + ', '.join(error_fields) if error_fields else '')

                    else:
                        messages.error(self.request, e.message)


                if success_message:
                    messages.success(self.request, success_message)
Ejemplo n.º 4
0
    def process_post_form(self, success_message=None):
        """
        As long as the form is set on the view this method will validate the form
        and save the submitted data.  Only call this if you are posting data.
        The given success_message will be used with the djanog messages framework
        if the posted data sucessfully submits.
        """

        # When on initial args are given we need to set the base document.
        if not hasattr(self, 'document') or self.document is None:
            self.document = self.document_type()
        self.form = MongoModelForm(
            model=self.document_type,
            instance=self.document,
            form_post_data=self.request.POST).get_form()
        self.form.is_bound = True
        if self.form.is_valid():

            self.document_map_dict = MongoModelForm(
                model=self.document_type).create_document_dictionary(
                    self.document_type)
            self.new_document = self.document_type

            # Used to keep track of embedded documents in lists.  Keyed by the list and the number of the
            # document.
            self.embedded_list_docs = {}

            if self.new_document is None:
                messages.error(self.request, u"Failed to save document")
            else:
                self.new_document = self.new_document()

                for form_key in self.form.cleaned_data.keys():
                    if form_key == 'id' and hasattr(self, 'document'):
                        self.new_document.id = self.document.id
                        continue
                    self.process_document(self.new_document, form_key, None)

                self.new_document.save()
                if success_message:
                    messages.success(self.request, success_message)

        return self.form
Ejemplo n.º 5
0
    def get_form(self, Form):
        self.set_mongonaut_base()
        self.document_type = getattr(self.models, self.document_name)
        self.form = Form()

        if self.request.method == 'POST':
            self.form = self.process_post_form('Your new document has been added and saved.')
        else:
            self.form = MongoModelForm(model=self.document_type).get_form()
        return self.form
Ejemplo n.º 6
0
    def get_form(self, form_class=None):
        self.set_mongonaut_base()
        self.document_type = getattr(self.models, self.document_name)
        self.form = super(DocumentAddFormView, self).get_form(form_class)

        if self.request.method == 'POST':
            self.form = self.process_post_form('Your new document has been added and saved.')
        else:
            self.form = MongoModelForm(model=self.document_type).get_form()
        return self.form
Ejemplo n.º 7
0
 def test_form_fields_ordering_inherit_from_model_meta_class(self):
     # if form_fields_ordering is set under model's Meta class,
     # ordering will be prioritized, then remaining fields are sorted
     ordered_author = OrderedUser(email=self.author.email,
                                  first_name=self.author.first_name,
                                  last_name=self.author.last_name)
     my_form = MongoModelForm(None,
                              model=OrderedUser,
                              instance=ordered_author).get_form()
     field_names = [field.name for field in my_form]
     self.assertEquals(field_names,
                       ['first_name', 'last_name', 'email', 'id'])
Ejemplo n.º 8
0
    def process_post_form(self, success_message=None):
        """
        As long as the form is set on the view this method will validate the form
        and save the submitted data.  Only call this if you are posting data.
        The given success_message will be used with the djanog messages framework
        if the posted data sucessfully submits.
        """

        # When on initial args are given we need to set the base document.
        if not hasattr(self, "document") or self.document is None:
            self.document = self.document_type()
        self.form = MongoModelForm(
            model=self.document_type, instance=self.document, form_post_data=self.request.POST
        ).get_form()
        self.form.is_bound = True
        if self.form.is_valid():

            self.document_map_dict = MongoModelForm(model=self.document_type).create_document_dictionary(
                self.document_type
            )
            self.new_document = self.document_type

            # Used to keep track of embedded documents in lists.  Keyed by the list and the number of the
            # document.
            self.embedded_list_docs = {}

            if self.new_document is None:
                messages.error(self.request, u"Failed to save document")
            else:
                self.new_document = self.new_document()

                for form_key in self.form.cleaned_data.keys():
                    if form_key == "id" and hasattr(self, "document"):
                        self.new_document.id = self.document.id
                        continue
                    self.process_document(self.new_document, form_key, None)

                self.new_document.save()
                if success_message:
                    messages.success(self.request, success_message)

        return self.form
Ejemplo n.º 9
0
class MongonautFormViewMixin(object):
    """
    View used to help with processing of posted forms.
    Must define self.document_type for process_post_form to work.
    """
    def process_post_form(self, success_message=None):
        """
        As long as the form is set on the view this method will validate the form
        and save the submitted data.  Only call this if you are posting data.
        The given success_message will be used with the djanog messages framework
        if the posted data sucessfully submits.
        """

        # When on initial args are given we need to set the base document.
        if not hasattr(self, 'document') or self.document is None:
            self.document = self.document_type()
        self.form = MongoModelForm(
            model=self.document_type,
            instance=self.document,
            form_post_data=self.request.POST).get_form()
        self.form.is_bound = True
        if self.form.is_valid():

            self.document_map_dict = MongoModelForm(
                model=self.document_type).create_document_dictionary(
                    self.document_type)
            self.new_document = self.document_type

            # Used to keep track of embedded documents in lists.  Keyed by the list and the number of the
            # document.
            self.embedded_list_docs = {}

            if self.new_document is None:
                messages.error(self.request, u"Failed to save document")
            else:
                self.new_document = self.new_document()

                for form_key in self.form.cleaned_data.keys():
                    if form_key == 'id' and hasattr(self, 'document'):
                        self.new_document.id = self.document.id
                        continue
                    self.process_document(self.new_document, form_key, None)

                self.new_document.save()
                if success_message:
                    messages.success(self.request, success_message)

        return self.form

    def process_document(self, document, form_key, passed_key):
        """
        Given the form_key will evaluate the document and set values correctly for
        the document given.
        """
        if passed_key is not None:
            current_key, remaining_key_array = trim_field_key(
                document, passed_key)
        else:
            current_key, remaining_key_array = trim_field_key(
                document, form_key)

        key_array_digit = remaining_key_array[
            -1] if remaining_key_array and has_digit(
                remaining_key_array) else None
        remaining_key = make_key(remaining_key_array)

        if current_key.lower() == 'id':
            raise KeyError(
                u"Mongonaut does not work with models which have fields beginning with id_"
            )

        # Create boolean checks to make processing document easier
        is_embedded_doc = (isinstance(document._fields.get(current_key, None),
                                      EmbeddedDocumentField) if hasattr(
                                          document, '_fields') else False)
        is_list = not key_array_digit is None
        key_in_fields = current_key in document._fields.keys() if hasattr(
            document, '_fields') else False

        # This ensures you only go through each documents keys once, and do not duplicate data
        if key_in_fields:
            if is_embedded_doc:
                self.set_embedded_doc(document, form_key, current_key,
                                      remaining_key)
            elif is_list:
                self.set_list_field(document, form_key, current_key,
                                    remaining_key, key_array_digit)
            else:
                value = translate_value(document._fields[current_key],
                                        self.form.cleaned_data[form_key])
                setattr(document, current_key, value)

    def set_embedded_doc(self, document, form_key, current_key, remaining_key):

        # Get the existing embedded document if it exists, else created it.
        embedded_doc = getattr(document, current_key, False)
        if not embedded_doc:
            embedded_doc = document._fields[current_key].document_type_obj()

        new_key, new_remaining_key_array = trim_field_key(
            embedded_doc, remaining_key)
        self.process_document(embedded_doc, form_key,
                              make_key(new_key, new_remaining_key_array))
        setattr(document, current_key, embedded_doc)

    def set_list_field(self, document, form_key, current_key, remaining_key,
                       key_array_digit):

        document_field = document._fields.get(current_key)

        # Figure out what value the list ought to have
        # None value for ListFields make mongoengine very un-happy
        list_value = translate_value(document_field.field,
                                     self.form.cleaned_data[form_key])
        if list_value is None or (not list_value and not bool(list_value)):
            return None

        current_list = getattr(document, current_key, None)

        if isinstance(document_field.field, EmbeddedDocumentField):
            embedded_list_key = u"{0}_{1}".format(current_key, key_array_digit)

            # Get the embedded document if it exists, else create it.
            embedded_list_document = self.embedded_list_docs.get(
                embedded_list_key, None)
            if embedded_list_document is None:
                embedded_list_document = document_field.field.document_type_obj(
                )

            new_key, new_remaining_key_array = trim_field_key(
                embedded_list_document, remaining_key)
            self.process_document(embedded_list_document, form_key, new_key)

            list_value = embedded_list_document
            self.embedded_list_docs[embedded_list_key] = embedded_list_document

            if isinstance(current_list, list):
                # Do not add the same document twice
                if embedded_list_document not in current_list:
                    current_list.append(embedded_list_document)
            else:
                setattr(document, current_key, [embedded_list_document])

        elif isinstance(current_list, list):
            current_list.append(list_value)
        else:
            setattr(document, current_key, [list_value])
Ejemplo n.º 10
0
class MongonautFormViewMixin(object):
    """
    View used to help with processing of posted forms.
    Must define self.document_type for process_post_form to work.
    """

    def process_post_form(self, success_message=None):
        """
        As long as the form is set on the view this method will validate the form
        and save the submitted data.  Only call this if you are posting data.
        The given success_message will be used with the djanog messages framework
        if the posted data sucessfully submits.
        """

        # When on initial args are given we need to set the base document.
        if not hasattr(self, "document") or self.document is None:
            self.document = self.document_type()
        self.form = MongoModelForm(
            model=self.document_type, instance=self.document, form_post_data=self.request.POST
        ).get_form()
        self.form.is_bound = True
        if self.form.is_valid():

            self.document_map_dict = MongoModelForm(model=self.document_type).create_document_dictionary(
                self.document_type
            )
            self.new_document = self.document_type

            # Used to keep track of embedded documents in lists.  Keyed by the list and the number of the
            # document.
            self.embedded_list_docs = {}

            if self.new_document is None:
                messages.error(self.request, u"Failed to save document")
            else:
                self.new_document = self.new_document()

                for form_key in self.form.cleaned_data.keys():
                    if form_key == "id" and hasattr(self, "document"):
                        self.new_document.id = self.document.id
                        continue
                    self.process_document(self.new_document, form_key, None)

                self.new_document.save()
                if success_message:
                    messages.success(self.request, success_message)

        return self.form

    def process_document(self, document, form_key, passed_key):
        """
        Given the form_key will evaluate the document and set values correctly for
        the document given.
        """
        if passed_key is not None:
            current_key, remaining_key_array = trim_field_key(document, passed_key)
        else:
            current_key, remaining_key_array = trim_field_key(document, form_key)

        key_array_digit = remaining_key_array[-1] if remaining_key_array and has_digit(remaining_key_array) else None
        remaining_key = make_key(remaining_key_array)

        if current_key.lower() == "id":
            raise KeyError(u"Mongonaut does not work with models which have fields beginning with id_")

        # Create boolean checks to make processing document easier
        is_embedded_doc = (
            isinstance(document._fields.get(current_key, None), EmbeddedDocumentField)
            if hasattr(document, "_fields")
            else False
        )
        is_list = not key_array_digit is None
        key_in_fields = current_key in document._fields.keys() if hasattr(document, "_fields") else False

        # This ensures you only go through each documents keys once, and do not duplicate data
        if key_in_fields:
            if is_embedded_doc:
                self.set_embedded_doc(document, form_key, current_key, remaining_key)
            elif is_list:
                self.set_list_field(document, form_key, current_key, remaining_key, key_array_digit)
            else:
                value = translate_value(document._fields[current_key], self.form.cleaned_data[form_key])
                setattr(document, current_key, value)

    def set_embedded_doc(self, document, form_key, current_key, remaining_key):

        # Get the existing embedded document if it exists, else created it.
        embedded_doc = getattr(document, current_key, False)
        if not embedded_doc:
            embedded_doc = document._fields[current_key].document_type_obj()

        new_key, new_remaining_key_array = trim_field_key(embedded_doc, remaining_key)
        self.process_document(embedded_doc, form_key, make_key(new_key, new_remaining_key_array))
        setattr(document, current_key, embedded_doc)

    def set_list_field(self, document, form_key, current_key, remaining_key, key_array_digit):

        document_field = document._fields.get(current_key)

        # Figure out what value the list ought to have
        # None value for ListFields make mongoengine very un-happy
        list_value = translate_value(document_field.field, self.form.cleaned_data[form_key])
        if list_value is None or (not list_value and not bool(list_value)):
            return None

        current_list = getattr(document, current_key, None)

        if isinstance(document_field.field, EmbeddedDocumentField):
            embedded_list_key = u"{0}_{1}".format(current_key, key_array_digit)

            # Get the embedded document if it exists, else create it.
            embedded_list_document = self.embedded_list_docs.get(embedded_list_key, None)
            if embedded_list_document is None:
                embedded_list_document = document_field.field.document_type_obj()

            new_key, new_remaining_key_array = trim_field_key(embedded_list_document, remaining_key)
            self.process_document(embedded_list_document, form_key, new_key)

            list_value = embedded_list_document
            self.embedded_list_docs[embedded_list_key] = embedded_list_document

            if isinstance(current_list, list):
                # Do not add the same document twice
                if embedded_list_document not in current_list:
                    current_list.append(embedded_list_document)
            else:
                setattr(document, current_key, [embedded_list_document])

        elif isinstance(current_list, list):
            current_list.append(list_value)
        else:
            setattr(document, current_key, [list_value])