Beispiel #1
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()
    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 add_form_element_entry(request,
                           form_entry_id,
                           form_element_plugin_uid,
                           theme=None,
                           template_name=None):
    """
    Add form element entry.

    :param django.http.HttpRequest request:
    :param int form_entry_id:
    :param int form_element_plugin_uid:
    :param fobi.base.BaseTheme theme: Theme instance.
    :param string template_name:
    :return django.http.HttpResponse:
    """
    try:
        form_entry = FormEntry._default_manager \
                              .prefetch_related('formelemententry_set') \
                              .get(pk=form_entry_id)
    except ObjectDoesNotExist as err:
        raise Http404(ugettext("Form entry not found."))

    form_elements = form_entry.formelemententry_set.all()

    user_form_element_plugin_uids = get_user_form_field_plugin_uids(
        request.user)

    if not form_element_plugin_uid in user_form_element_plugin_uids:
        raise Http404(
            ugettext("Plugin does not exist or you are not allowed "
                     "to use this plugin!"))

    FormElementPlugin = form_element_plugin_registry.get(
        form_element_plugin_uid)
    form_element_plugin = FormElementPlugin(user=request.user)
    form_element_plugin.request = request

    FormElementPluginForm = form_element_plugin.get_form()
    form = None

    obj = FormElementEntry()
    obj.form_entry = form_entry
    obj.plugin_uid = form_element_plugin_uid
    obj.user = request.user

    save_object = False

    # If plugin doesn't have a form
    if not FormElementPluginForm:
        save_object = True

    # If POST
    elif 'POST' == request.method:
        # If element has a form
        form = form_element_plugin.get_initialised_create_form_or_404(
            data=request.POST, files=request.FILES)
        form.validate_plugin_data(form_elements, request=request)
        if form.is_valid():
            # Saving the plugin form data.
            form.save_plugin_data(request=request)

            # Getting the plugin data.
            obj.plugin_data = form.get_plugin_data(request=request)

            save_object = True

    # If not POST
    else:
        form = form_element_plugin.get_initialised_create_form_or_404()

    if save_object:
        # Handling the position
        position = 1
        records = FormElementEntry._default_manager \
                                  .aggregate(models.Max('position'))
        if records:
            try:
                position = records['{0}__max'.format('position')] + 1

            except TypeError as err:
                pass

        obj.position = position

        # Save the object.
        obj.save()

        messages.info(
            request,
            _('The form element plugin "{0}" was added '
              'successfully.').format(form_element_plugin.name))
        return redirect("{0}?active_tab=tab-form-elemenets".format(
            reverse('fobi.edit_form_entry',
                    kwargs={'form_entry_id': form_entry_id})))

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

    # If given, pass to the template (and override the value set by
    # the context processor.
    if theme:
        context.update({'fobi_theme': theme})

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

    return render_to_response(template_name,
                              context,
                              context_instance=RequestContext(request))
Beispiel #4
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 #5
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 #6
0
def add_form_element_entry(request, form_entry_id, form_element_plugin_uid,
                           theme=None, template_name=None):
    """
    Add form element entry.

    :param django.http.HttpRequest request:
    :param int form_entry_id:
    :param int form_element_plugin_uid:
    :param string template_name:
    :return django.http.HttpResponse:
    """
    try:
        form_entry = FormEntry._default_manager \
                              .prefetch_related('formelemententry_set') \
                              .get(pk=form_entry_id)
    except ObjectDoesNotExist as err:
        raise Http404(ugettext("Form entry not found."))

    form_elements = form_entry.formelemententry_set.all()

    user_form_element_plugin_uids = get_user_form_field_plugin_uids(
        request.user
        )

    if not form_element_plugin_uid in user_form_element_plugin_uids:
        raise Http404(ugettext("Plugin does not exist or you are not allowed "
                        "to use this plugin!"))

    FormElementPlugin = form_element_plugin_registry.get(
        form_element_plugin_uid
        )
    form_element_plugin = FormElementPlugin(user=request.user)
    form_element_plugin.request = request

    FormElementPluginForm = form_element_plugin.get_form()
    form = None

    obj = FormElementEntry()
    obj.form_entry = form_entry
    obj.plugin_uid = form_element_plugin_uid
    obj.user = request.user

    save_object = False

    # If plugin doesn't have a form
    if not FormElementPluginForm:
        save_object = True

    # If POST
    elif 'POST' == request.method:
        # If element has a form
        form = form_element_plugin.get_initialised_create_form_or_404(
            data = request.POST,
            files = request.FILES
            )
        form.validate_plugin_data(form_elements, request=request)
        if form.is_valid():
            # Saving the plugin form data.
            form.save_plugin_data(request=request)

            # Getting the plugin data.
            obj.plugin_data = form.get_plugin_data(request=request)

            save_object = True

    # If not POST
    else:
        form = form_element_plugin.get_initialised_create_form_or_404()

    if save_object:
        # Handling the position
        position = 1
        records = FormElementEntry._default_manager \
                                  .aggregate(models.Max('position'))
        if records:
            try:
                position = records['{0}__max'.format('position')] + 1

            except TypeError as err:
                pass

        obj.position = position

        # Save the object.
        obj.save()

        messages.info(
            request,
            _('The form element plugin "{0}" was added '
              'successfully.').format(form_element_plugin.name)
            )
        return redirect(
            "{0}?active_tab=tab-form-elemenets".format(
                reverse('fobi.edit_form_entry',
                        kwargs={'form_entry_id': form_entry_id})
                )
            )

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

    # If given, pass to the template (and override the value set by
    # the context processor.
    if theme:
        context.update({'fobi_theme': theme})

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

    return render_to_response(template_name, context,
                              context_instance=RequestContext(request))
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