def import_data(self):
        """
        Imports data.
        """
        # TODO: Move this to top level and ensure it works!
        from fobi.models import FormEntry, FormElementEntry
        assert 'name' in self.form_properties
        form_entry = FormEntry()
        for prop, val in self.form_properties.items():
            setattr(form_entry, prop, val)

        form_entry.save()

        data = self.get_form_data()
        for field_data in data:
            # Skip non-existing
            if not field_data[self.field_type_prop_name] in self.fields_mapping:
                continue

            form_element_entry = FormElementEntry()
            form_element_entry.form_entry = form_entry
            form_element_entry.plugin_uid = self.fields_mapping[field_data[self.field_type_prop_name]]

            # Assign form data
            form_element_entry.plugin_data = json.dumps(
                self.extract_field_properties(field_data)
                )

            # Assign position in form
            if self.position_prop_name in field_data:
                form_element_entry.position = field_data[self.position_prop_name]

            form_element_entry.save()
Beispiel #2
0
    def import_data(self):
        """
        Imports data.
        """
        # TODO: Move this to top level and ensure it works!
        from fobi.models import FormEntry, FormElementEntry
        assert 'name' in self.form_properties
        form_entry = FormEntry()
        for prop, val in self.form_properties.items():
            setattr(form_entry, prop, val)

        form_entry.save()

        data = self.get_form_data()
        for field_data in data:
            # Skip non-existing
            if not field_data[self.field_type_prop_name] in self.fields_mapping:
                continue

            form_element_entry = FormElementEntry()
            form_element_entry.form_entry = form_entry
            form_element_entry.plugin_uid = self.fields_mapping[field_data[self.field_type_prop_name]]

            # Assign form data
            form_element_entry.plugin_data = json.dumps(
                self.extract_field_properties(field_data)
                )

            # Assign position in form
            if self.position_prop_name in field_data:
                form_element_entry.position = field_data[self.position_prop_name]

            form_element_entry.save()
Beispiel #3
0
    def _create_form_entry(self):
        user = get_or_create_admin_user()
        self.assertTrue(user is not None)

        form_entry = FormEntry(name=TEST_FORM_NAME,
                               slug=TEST_FORM_SLUG,
                               user=user)
        form_entry.save()
        return form_entry
Beispiel #4
0
    def _create_form_entry(self):
        user = get_or_create_admin_user()
        self.assertTrue(user is not None)

        form_entry = FormEntry(
            name = TEST_FORM_NAME,
            slug = TEST_FORM_SLUG,
            user = user
            )
        form_entry.save()
        return form_entry
Beispiel #5
0
def import_form_entry(request, template_name=None):
    """
    Import form entry.

    :param django.http.HttpRequest request:
    :param string template_name:
    :return django.http.HttpResponse:
    """
    if 'POST' == request.method:
        form = ImportFormEntryForm(request.POST, request.FILES)

        if form.is_valid():
            # Reading the contents of the file into JSON
            json_file = form.cleaned_data['file']
            file_contents = json_file.read()

            # This is the form data which we are going to use when recreating
            # the form.
            form_data = json.loads(file_contents)

            # Since we just feed all the data to the `FormEntry` class,
            # we need to make sure it doesn't have strange fields in.
            # Furthermore, we will use the `form_element_data` and
            # `form_handler_data` for filling the missing plugin data.
            form_elements_data = form_data.pop('form_elements', [])
            form_handlers_data = form_data.pop('form_handlers', [])

            # User information we always recreate!
            form_data['user'] = request.user

            form_entry = FormEntry(**form_data)

            form_entry.name += ugettext(" (imported on {0})").format(
                datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            form_entry.save()

            # One by one, importing form element plugins.
            for form_element_data in form_elements_data:
                if form_element_plugin_registry._registry.get(
                        form_element_data.get('plugin_uid', None), None):
                    form_element = FormElementEntry(**form_element_data)
                    form_element.form_entry = form_entry
                    form_element.save()
                else:
                    if form_element_data.get('plugin_uid', None):
                        messages.warning(
                            request,
                            _('Plugin {0} is missing in the system.'
                              '').format(form_element_data.get('plugin_uid')))
                    else:
                        messages.warning(
                            request,
                            _('Some essential plugin data missing in the JSON '
                              'import.'))

            # One by one, importing form handler plugins.
            for form_handler_data in form_handlers_data:
                if form_handler_plugin_registry._registry.get(
                        form_handler_data.get('plugin_uid', None), None):
                    form_handler = FormHandlerEntry(**form_handler_data)
                    form_handler.form_entry = form_entry
                    form_handler.save()
                else:
                    if form_handler.get('plugin_uid', None):
                        messages.warning(
                            request,
                            _('Plugin {0} is missing in the system.'
                              '').format(form_handler.get('plugin_uid')))
                    else:
                        messages.warning(
                            request,
                            _('Some essential data missing in the JSON '
                              'import.'))

            messages.info(request, _('The form was imported successfully.'))
            return redirect('fobi.edit_form_entry',
                            form_entry_id=form_entry.pk)
    else:
        form = ImportFormEntryForm()

    # When importing entries from saved JSON we shouldn't just save
    # them into database and consider it done, since there might be cases
    # if a certain plugin doesn't exist in the system, which will lead
    # to broken form entries. Instead, we should check every single
    # form-element or form-handler plugin for existence. If not doesn't exist
    # in the system, we might: (1) roll entire transaction back or (2) ignore
    # broken entries. The `ImportFormEntryForm` form has two fields to
    # additional fields which serve the purpose:
    # `ignore_broken_form_element_entries` and
    # `ignore_broken_form_handler_entries`. When set to True, when a broken
    # form element/handler plugin has been discovered, the import would
    # continue, having the broken form element/handler entries not imported.

    context = {
        'form': form,
        #'form_entry': form_entry
    }

    if not template_name:
        theme = get_theme(request=request, as_instance=True)
        template_name = theme.import_form_entry_template

    return render_to_response(template_name,
                              context,
                              context_instance=RequestContext(request))
Beispiel #6
0
def create_form_with_entries(user=None, create_entries_if_form_exist=True):
    """
    Create test form with entries. Fills the form with pre-defined
    plugins.

    :param django.contrib.auth.models.User user:
    :param bool create_entries_if_form_exist: If set to True, entries
        are being created even if form already exists (a database
        record).
    :return fobi.models.FormEntry: Instance of ``fobi.models.FormEntry``
        with a number of form elements and handlers filled in.
    """
    if not user:
        user = get_or_create_admin_user()

    try:
        form_entry = FormEntry._default_manager.get(slug=TEST_FORM_SLUG)
        if not create_entries_if_form_exist:
            return None
    except Exception as e:
        form_entry = FormEntry(
            name = TEST_FORM_NAME,
            slug = TEST_FORM_SLUG,
            user = user
            )
        form_entry.save()

    # *************************************************************************
    # ******************************** Form elements **************************
    # *************************************************************************
    position = 1
    # Text input
    form_element_entry = FormElementEntry(
        form_entry = form_entry,
        plugin_uid = TextInputPlugin.uid,
        plugin_data = '{"name": "username", "required": true, '
                      '"max_length": "200", "label": "Username"}',
        position = position
        )
    form_element_entry.save()
    position += 1

    # Email
    form_element_entry = FormElementEntry(
        form_entry = form_entry,
        plugin_uid = EmailInputPlugin.uid,
        plugin_data = '{"name": "email", "required": true, "label": "E-mail"}',
        position = position
        )
    form_element_entry.save()
    position += 1

    # Integer
    form_element_entry = FormElementEntry(
        form_entry = form_entry,
        plugin_uid = IntegerInputPlugin.uid,
        plugin_data = '{"name": "age", "required": true, '
                      '"max_value": "200", "label": "Age"}',
        position = position
        )
    form_element_entry.save()
    position += 1

    # Boolean select
    form_element_entry = FormElementEntry(
        form_entry = form_entry,
        plugin_uid = BooleanSelectPlugin.uid,
        plugin_data = '{"name": "drivers_license", "required": false, '
                      '"label": "Drivers license?"}',
        position = position
        )
    form_element_entry.save()
    position += 1

    # Hidden
    form_element_entry = FormElementEntry(
        form_entry = form_entry,
        plugin_uid = HiddenInputPlugin.uid,
        plugin_data = '{"name": "special_fields", "required": false, '
                      '"label": "Special fields"}',
        position = position
        )
    form_element_entry.save()
    position += 1

    # Content image
    form_element_entry = FormElementEntry(
        form_entry = form_entry,
        plugin_uid = ContentImagePlugin.uid,
        plugin_data = '{"fit_method": "center", '
                      '"file": "fobi_plugins/content_plugin_images/04.jpg", '
                      '"alt": "Cute girl"}',
        position = position
        )
    form_element_entry.save()
    position += 1

    # Integer
    form_element_entry = FormElementEntry(
        form_entry = form_entry,
        plugin_uid = IntegerInputPlugin.uid,
        plugin_data = '{"name": "number_of_children", "required": false, '
                      '"label": "Number of children"}',
        position = position
        )
    form_element_entry.save()
    position += 1

    # Textarea
    form_element_entry = FormElementEntry(
        form_entry = form_entry,
        plugin_uid = TextareaPlugin.uid,
        plugin_data = '{"name": "bio", "required": true, "label": "Biography"}',
        position = position
        )
    form_element_entry.save()
    position += 1

    # Content text
    form_element_entry = FormElementEntry(
        form_entry = form_entry,
        plugin_uid = ContentTextPlugin.uid,
        plugin_data = ''
            '{"text": "Suspendisse potenti. Etiam in nunc sodales, congue '
            'lectus ut, suscipit massa. In commodo fringilla orci, in varius '
            'eros gravida a! Aliquam erat volutpat. Donec sodales orci nec '
            'massa aliquam bibendum. Aenean sed condimentum velit. Mauris '
            'luctus bibendum nulla vel tempus. Integer tempor condimentum '
            'ligula sed feugiat. Aenean scelerisque ultricies vulputate. '
            'Donec semper lorem rhoncus sem cras amet."}',
        position = 9
        )
    form_element_entry.save()
    position += 1

    # *************************************************************************
    # ******************************** Form handlers **************************
    # *************************************************************************

    # DB save
    form_handler_entry = FormHandlerEntry(
        form_entry = form_entry,
        plugin_uid = DBStoreHandlerPlugin.uid,
        plugin_data = ''
        )
    form_handler_entry.save()

    # Mail
    form_handler_entry = FormHandlerEntry(
        form_entry = form_entry,
        plugin_uid = MailHandlerPlugin.uid,
        plugin_data = '{"from_name": "Fobi administration", '
                      '"from_email": "*****@*****.**", '
                      '"to_name": "Artur Barseghyan", '
                      '"to_email": "*****@*****.**", '
                      '"subject": "Test mail", "body": "Test body"}'
        )
    form_handler_entry.save()

    return form_entry
Beispiel #7
0
def import_form_entry(request, template_name=None):
    """
    Import form entry.

    :param django.http.HttpRequest request:
    :param string template_name:
    :return django.http.HttpResponse:
    """
    if 'POST' == request.method:
        form = ImportFormEntryForm(request.POST, request.FILES)

        if form.is_valid():
            # Reading the contents of the file into JSON
            file = form.cleaned_data['file']
            file_contents = file.read()

            # This is the form data which we are going to use when recreating
            # the form.
            form_data = json.loads(file_contents)

            # Since we just feed all the data to the `FormEntry` class,
            # we need to make sure it doesn't have strange fields in.
            # Furthermore, we will use the `form_element_data` and
            # `form_handler_data` for filling the missing plugin data.
            form_elements_data = form_data.pop('form_elements', [])
            form_handlers_data = form_data.pop('form_handlers', [])

            # User information we always recreate!
            form_data['user'] = request.user

            form_entry = FormEntry(**form_data)

            form_entry.name += ugettext(" (imported on {0})").format(
                datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            )
            form_entry.save()

            # One by one, importing form element plugins.
            for form_element_data in form_elements_data:
                if form_element_plugin_registry._registry.get(
                        form_element_data.get('plugin_uid', None), None):
                    form_element = FormElementEntry(**form_element_data)
                    form_element.form_entry = form_entry
                    form_element.save()
                else:
                    if form_element_data.get('plugin_uid', None):
                       messages.warning(
                            request,
                            _('Plugin {0} is missing in the system.').format(
                                form_element_data.get('plugin_uid')
                                )
                            )
                    else:
                        messages.warning(
                            request,
                            _('Some essential plugin data missing in the JSON '
                              'import.')
                            )

            # One by one, importing form handler plugins.
            for form_handler_data in form_handlers_data:
                if form_handler_plugin_registry._registry.get(
                        form_handler_data.get('plugin_uid', None), None):
                    form_handler = FormHandlerEntry(**form_handler_data)
                    form_handler.form_entry = form_entry
                    form_handler.save()
                else:
                    if form_handler.get('plugin_uid', None):
                       messages.warning(
                            request,
                            _('Plugin {0} is missing in the system.').format(
                                form_handler.get('plugin_uid')
                                )
                            )
                    else:
                        messages.warning(
                            request,
                            _('Some essential data missing in the JSON '
                              'import.')
                            )


            messages.info(
                request,
                _('The form was imported successfully.')
                )
            return redirect(
                    'fobi.edit_form_entry', form_entry_id=form_entry.pk
                    )
    else:
        form = ImportFormEntryForm()

    # When importing entries from saved JSON we shouldn't just save
    # them into database and consider it done, since there might be cases
    # if a certain plugin doesn't exist in the system, which will lead
    # to broken form entries. Instead, we should check every single
    # form-element or form-handler plugin for existence. If not doesn't exist
    # in the system, we might: (1) roll entire transaction back or (2) ignore
    # broken entries. The `ImportFormEntryForm` form has two fields to
    # additional fields which serve the purpose:
    # `ignore_broken_form_element_entries` and
    # `ignore_broken_form_handler_entries`. When set to True, when a broken
    # form element/handler plugin has been discovered, the import would
    # continue, having the broken form element/handler entries not imported.

    context = {
        'form': form,
        #'form_entry': form_entry
    }

    if not template_name:
        theme = get_theme(request=request, as_instance=True)
        template_name = theme.import_form_entry_template

    return render_to_response(template_name, context,
                              context_instance=RequestContext(request))
Beispiel #8
0
def create_form_with_entries(user=None,
                             create_entries_if_form_exist=True,
                             data={},
                             is_public=False,
                             name=TEST_FORM_NAME,
                             slug=TEST_FORM_SLUG):
    """Create test form with entries.

    Fills the form with pre-defined plugins.

    :param django.contrib.auth.models.User user:
    :param bool create_entries_if_form_exist: If set to True, entries
        are being created even if form already exists (a database
        record).
    :param dict data:
    :param bool is_public:
    :param str name:
    :param str slug:
    :return fobi.models.FormEntry: Instance of ``fobi.models.FormEntry``
        with a number of form elements and handlers filled in.
    """
    if not user:
        user = get_or_create_admin_user()

    try:
        form_entry = FormEntry._default_manager.get(slug=slug)
        if not create_entries_if_form_exist:
            return None
    except Exception as err:
        form_entry = FormEntry(
            name=name,
            slug=slug,
            user=user,
            is_public=is_public,
        )
        form_entry.save()

    # ************************************************************************
    # ******************************** Form elements *************************
    # ************************************************************************
    position = 1
    for key, entry_data in data.items():
        form_element_entry = FormElementEntry(form_entry=form_entry,
                                              plugin_uid=entry_data[0],
                                              plugin_data=entry_data[1],
                                              position=position)
        form_element_entry.save()
        position += 1

    # ************************************************************************
    # ******************************** Form handlers *************************
    # ************************************************************************

    # DB save
    form_handler_entry = FormHandlerEntry(form_entry=form_entry,
                                          plugin_uid=DBStoreHandlerPlugin.uid,
                                          plugin_data='')
    form_handler_entry.save()

    # Mail
    form_handler_entry = FormHandlerEntry(
        form_entry=form_entry,
        plugin_uid=MailHandlerPlugin.uid,
        plugin_data='{'
        '"from_name": "Fobi administration", '
        '"from_email": "*****@*****.**", '
        '"to_name": "Artur Barseghyan", '
        '"to_email": "*****@*****.**", '
        '"subject": "Test mail", "body": "Test body"'
        '}')
    form_handler_entry.save()

    return form_entry
Beispiel #9
0
def create_form_with_entries(user=None, create_entries_if_form_exist=True):
    """Create test form with entries.

    Fills the form with pre-defined plugins.

    :param django.contrib.auth.models.User user:
    :param bool create_entries_if_form_exist: If set to True, entries
        are being created even if form already exists (a database
        record).
    :return fobi.models.FormEntry: Instance of ``fobi.models.FormEntry``
        with a number of form elements and handlers filled in.
    """
    if not user:
        user = get_or_create_admin_user()

    try:
        form_entry = FormEntry._default_manager.get(slug=TEST_FORM_SLUG)
        if not create_entries_if_form_exist:
            return None
    except Exception as err:
        form_entry = FormEntry(
            name=TEST_FORM_NAME,
            slug=TEST_FORM_SLUG,
            user=user
        )
        form_entry.save()

    # *************************************************************************
    # ******************************** Form elements **************************
    # *************************************************************************
    position = 1
    # Text input
    form_element_entry = FormElementEntry(
        form_entry=form_entry,
        plugin_uid=TextInputPlugin.uid,
        plugin_data='{"name": "username", "required": true, '
                    '"max_length": "200", "label": "Username"}',
        position=position
    )
    form_element_entry.save()
    position += 1

    # Email
    form_element_entry = FormElementEntry(
        form_entry=form_entry,
        plugin_uid=EmailInputPlugin.uid,
        plugin_data='{"name": "email", "required": true, "label": "E-mail"}',
        position=position
    )
    form_element_entry.save()
    position += 1

    # Integer
    form_element_entry = FormElementEntry(
        form_entry=form_entry,
        plugin_uid=IntegerInputPlugin.uid,
        plugin_data='{"name": "age", "required": true, '
                    '"max_value": "200", "label": "Age"}',
        position=position
    )
    form_element_entry.save()
    position += 1

    # Boolean select
    form_element_entry = FormElementEntry(
        form_entry=form_entry,
        plugin_uid=BooleanSelectPlugin.uid,
        plugin_data='{"name": "drivers_license", "required": false, '
                    '"label": "Drivers license?"}',
        position=position
    )
    form_element_entry.save()
    position += 1

    # Hidden
    form_element_entry = FormElementEntry(
        form_entry=form_entry,
        plugin_uid=HiddenInputPlugin.uid,
        plugin_data='{"name": "special_fields", "required": false, '
                    '"label": "Special fields"}',
        position=position
    )
    form_element_entry.save()
    position += 1

    # Content image
    form_element_entry = FormElementEntry(
        form_entry=form_entry,
        plugin_uid=ContentImagePlugin.uid,
        plugin_data='{"fit_method": "center", '
                    '"file": "fobi_plugins/content_plugin_images/04.jpg", '
                    '"alt": "Cute girl"}',
        position=position
    )
    form_element_entry.save()
    position += 1

    # Integer
    form_element_entry = FormElementEntry(
        form_entry=form_entry,
        plugin_uid=IntegerInputPlugin.uid,
        plugin_data='{"name": "number_of_children", "required": false, '
                    '"label": "Number of children"}',
        position=position
    )
    form_element_entry.save()
    position += 1

    # Textarea
    form_element_entry = FormElementEntry(
        form_entry=form_entry,
        plugin_uid=TextareaPlugin.uid,
        plugin_data='{"name": "bio", "required": true, "label": "Biography"}',
        position=position
    )
    form_element_entry.save()
    position += 1

    # Content text
    form_element_entry = FormElementEntry(
        form_entry=form_entry,
        plugin_uid=ContentTextPlugin.uid,
        plugin_data=''
                    '{"text": "Suspendisse potenti. Etiam in nunc sodales, '
                    'congue lectus ut, suscipit massa. In commodo fringilla '
                    'orci, in varius eros gravida a! Aliquam erat volutpat. '
                    'Donec sodales orci nec massa aliquam bibendum. Aenean sed '
                    'condimentum velit. Mauris luctus bibendum nulla vel '
                    'tempus. Integer tempor condimentum ligula sed feugiat. '
                    'Aenean scelerisque ultricies vulputate. Donec semper '
                    'lorem rhoncus sem cras amet."}',
        position=9
    )
    form_element_entry.save()
    position += 1

    # *************************************************************************
    # ******************************** Form handlers **************************
    # *************************************************************************

    # DB save
    form_handler_entry = FormHandlerEntry(
        form_entry=form_entry,
        plugin_uid=DBStoreHandlerPlugin.uid,
        plugin_data=''
    )
    form_handler_entry.save()

    # Mail
    form_handler_entry = FormHandlerEntry(
        form_entry=form_entry,
        plugin_uid=MailHandlerPlugin.uid,
        plugin_data='{"from_name": "Fobi administration", '
                    '"from_email": "*****@*****.**", '
                    '"to_name": "Artur Barseghyan", '
                    '"to_email": "*****@*****.**", '
                    '"subject": "Test mail", "body": "Test body"}'
    )
    form_handler_entry.save()

    return form_entry
Beispiel #10
0
def create_form_with_entries(user=None,
                             create_entries_if_form_exist=True,
                             data={},
                             is_public=False,
                             name=TEST_FORM_NAME,
                             slug=TEST_FORM_SLUG):
    """Create test form with entries.

    Fills the form with pre-defined plugins.

    :param django.contrib.auth.models.User user:
    :param bool create_entries_if_form_exist: If set to True, entries
        are being created even if form already exists (a database
        record).
    :param dict data:
    :param bool is_public:
    :param str name:
    :param str slug:
    :return fobi.models.FormEntry: Instance of ``fobi.models.FormEntry``
        with a number of form elements and handlers filled in.
    """
    if not user:
        user = get_or_create_admin_user()

    try:
        form_entry = FormEntry._default_manager.get(slug=slug)
        if not create_entries_if_form_exist:
            return None
    except Exception as err:
        form_entry = FormEntry(
            name=name,
            slug=slug,
            user=user,
            is_public=is_public,
        )
        form_entry.save()

    # ************************************************************************
    # ******************************** Form elements *************************
    # ************************************************************************
    position = 1
    for key, entry_data in data.items():
        form_element_entry = FormElementEntry(
            form_entry=form_entry,
            plugin_uid=entry_data[0],
            plugin_data=entry_data[1],
            position=position
        )
        form_element_entry.save()
        position += 1

    # ************************************************************************
    # ******************************** Form handlers *************************
    # ************************************************************************

    # DB save
    form_handler_entry = FormHandlerEntry(
        form_entry=form_entry,
        plugin_uid=DBStoreHandlerPlugin.uid,
        plugin_data=''
    )
    form_handler_entry.save()

    # Mail
    form_handler_entry = FormHandlerEntry(
        form_entry=form_entry,
        plugin_uid=MailHandlerPlugin.uid,
        plugin_data='{'
                    '"from_name": "Fobi administration", '
                    '"from_email": "*****@*****.**", '
                    '"to_name": "Artur Barseghyan", '
                    '"to_email": "*****@*****.**", '
                    '"subject": "Test mail", "body": "Test body"'
                    '}'
    )
    form_handler_entry.save()

    return form_entry