示例#1
0
    def run(self, form_entry, request, form, form_element_entries=None):
        """
        :param fobi.models.FormEntry form_entry: Instance of
            ``fobi.models.FormEntry``.
        :param django.http.HttpRequest request:
        :param django.forms.Form form:
        :param iterable form_element_entries: Iterable of
            ``fobi.models.FormElementEntry`` objects.
        """
        base_url = 'http{secure}://{host}'.format(
            secure=('s' if request.is_secure() else ''),
            host=request.get_host())

        # Clean up the values, leave our content fields and empty values.
        field_name_to_label_map, cleaned_data = get_processed_form_data(
            form, form_element_entries)

        rendered_data = []
        for key, value in cleaned_data.items():
            if value and isinstance(value, string_types) and value.startswith(
                    settings.MEDIA_URL):
                cleaned_data[key] = '{base_url}{value}'.format(
                    base_url=base_url, value=value)
            label = field_name_to_label_map.get(key, key)
            rendered_data.append('{0}: {1}\n'.format(
                safe_text(label), safe_text(cleaned_data[key])))

        send_mail(safe_text(self.data.subject),
                  "{0}\n\n{1}".format(safe_text(self.data.body),
                                      ''.join(rendered_data)),
                  self.data.from_email, [self.data.to_email],
                  fail_silently=True)
示例#2
0
文件: base.py 项目: rds0751/newapr
    def prepare_plugin_form_data(self, cleaned_data):
        """Prepare plugin form data.

        Might be used in integration plugins.
        """
        # In case if we should submit value as is, we don't return anything.
        # In other cases, we proceed further.

        # Get the object
        obj = cleaned_data.get(self.data.name, None)
        if obj:
            value = None
            # Should be returned as repr
            if SUBMIT_VALUE_AS == SUBMIT_VALUE_AS_REPR:
                value = safe_text(obj)
            elif SUBMIT_VALUE_AS == SUBMIT_VALUE_AS_VAL:
                value = '{0}.{1}.{2}'.format(obj._meta.app_label,
                                             get_model_name_for_object(obj),
                                             obj.pk)
            else:
                # Handle the submitted form value
                value = '{0}.{1}.{2}.{3}'.format(
                    obj._meta.app_label, get_model_name_for_object(obj),
                    obj.pk, safe_text(obj))

            # Overwrite ``cleaned_data`` of the ``form`` with object
            # qualifier.
            cleaned_data[self.data.name] = value

            # It's critically important to return the ``form`` with updated
            # ``cleaned_data``
            return cleaned_data
示例#3
0
    def submit_plugin_form_data(self, form_entry, request, form):
        """Submit plugin form data/process.

        :param fobi.models.FormEntry form_entry: Instance of
            ``fobi.models.FormEntry``.
        :param django.http.HttpRequest request:
        :param django.forms.Form form:
        """
        # In case if we should submit value as is, we don't return anything.
        # In other cases, we proceed further.

        # Get the object
        obj = form.cleaned_data.get(self.data.name, None)
        if obj:
            value = None
            # Should be returned as repr
            if SUBMIT_VALUE_AS == SUBMIT_VALUE_AS_REPR:
                value = safe_text(obj)
            elif SUBMIT_VALUE_AS == SUBMIT_VALUE_AS_VAL:
                value = '{0}.{1}.{2}'.format(obj._meta.app_label,
                                             get_model_name_for_object(obj),
                                             obj.pk)
            else:
                # Handle the submitted form value
                value = '{0}.{1}.{2}.{3}'.format(
                    obj._meta.app_label, get_model_name_for_object(obj),
                    obj.pk, safe_text(obj))

            # Overwrite ``cleaned_data`` of the ``form`` with object
            # qualifier.
            form.cleaned_data[self.data.name] = value

        # It's critically important to return the ``form`` with updated
        # ``cleaned_data``
        return form
示例#4
0
    def run(self,
            form_wizard_entry,
            request,
            form_list,
            form_wizard,
            form_element_entries=None):
        """Run.

        :param fobi.models.FormWizardEntry form_wizard_entry: Instance
            of :class:`fobi.models.FormWizardEntry`.
        :param django.http.HttpRequest request:
        :param list form_list: List of :class:`django.forms.Form` instances.
        :param fobi.wizard.views.dynamic.DynamicWizardView form_wizard:
            Instance of :class:`fobi.wizard.views.dynamic.DynamicWizardView`.
        :param iterable form_element_entries: Iterable of
            ``fobi.models.FormElementEntry`` objects.
        """
        base_url = 'http{secure}://{host}'.format(
            secure=('s' if request.is_secure() else ''),
            host=request.get_host())

        if not form_element_entries:
            form_element_entries = \
                get_form_element_entries_for_form_wizard_entry(
                    form_wizard_entry
                )

        # Clean up the values, leave our content fields and empty values.
        field_name_to_label_map, cleaned_data = get_processed_form_wizard_data(
            form_wizard, form_list, form_element_entries)

        rendered_data = []
        for key, value in cleaned_data.items():
            if value and isinstance(value, string_types) \
                     and value.startswith(settings.MEDIA_URL):
                cleaned_data[key] = '{base_url}{value}'.format(
                    base_url=base_url, value=value)
            label = field_name_to_label_map.get(key, key)
            rendered_data.append('{0}: {1}\n'.format(
                safe_text(label), safe_text(cleaned_data[key])))

        files = self._prepare_files(request, form_list)

        # Handling more than one email address
        if isinstance(self.data.to_email, (list, tuple)):
            to_email = self.data.to_email
        else:
            # Assume that it's string
            to_email = self.data.to_email.split(
                MULTI_EMAIL_FIELD_VALUE_SPLITTER)

        send_mail(safe_text(self.data.subject),
                  "{0}\n\n{1}".format(safe_text(self.data.body),
                                      ''.join(rendered_data)),
                  self.data.from_email,
                  to_email,
                  fail_silently=False,
                  attachments=files.values())
示例#5
0
    def plugin_data_repr(self):
        """
        Human readable representation of plugin data.

        :return string:
        """
        context = {
            'to_name': safe_text(self.data.to_name),
            'to_email': self.data.to_email,
            'subject': safe_text(self.data.subject),
        }
        return render_to_string('mail/plugin_data_repr.html', context)
示例#6
0
    def plugin_data_repr(self):
        """
        Human readable representation of plugin data.

        :return string:
        """
        context = {
            'to_name': safe_text(self.data.to_name),
            'to_email': self.data.to_email,
            'subject': safe_text(self.data.subject),
        }
        return render_to_string('mail/plugin_data_repr.html', context)
示例#7
0
def append_edit_and_delete_links_to_field(form_element_plugin, \
                                          form_element_entry, origin=None, \
                                          extra={}, widget_cls=None):
    """
    Should return dictionary, which would be used to update default kwargs
    of form fields.

    The hidden inputs `form-{counter}-position` and `form-{counter}-id` are
    for saving the ordering of the elements (`position` field).

    :return dict:
    """
    theme = get_theme(as_instance=True)
    PluginForm = form_element_plugin.get_form()
    counter = extra.get('counter')
    edit_url = reverse(
        'fobi.edit_form_element_entry',
        kwargs = {'form_element_entry_id': form_element_entry.pk}
        )

    edit_option_html = theme.edit_form_entry_edit_option_html().format(
        edit_url = edit_url,
        edit_text = safe_text(ugettext("Edit")),
        )
    help_text_extra = theme.edit_form_entry_help_text_extra().format(
        edit_option_html = edit_option_html if PluginForm else '',
        delete_url = reverse('fobi.delete_form_element_entry', kwargs={'form_element_entry_id': form_element_entry.pk}),
        delete_text = safe_text(ugettext("Delete")),
        form_element_pk = form_element_entry.pk,
        form_element_position = form_element_entry.position,
        counter = counter
        )
    try:
        help_text = safe_text(form_element_plugin.data.help_text)
    except:
        help_text = ''

    d = {
        'help_text': "{0} {1}".format(help_text, help_text_extra),
    }

    label = safe_text(getattr(form_element_plugin.data, 'label', ''))
    d.update({'label': "{0} ({1})".format(label, safe_text(form_element_plugin.name))})

    #if 'hidden' == form_element_plugin.uid:
    #    d.update({'widget': TextInput(attrs={'class': theme.form_element_html_class})})
    if widget_cls:
        d.update({'widget': widget_cls(attrs={'class': theme.form_element_html_class})})
    elif form_element_plugin.is_hidden:
        d.update({'widget': TextInput(attrs={'class': theme.form_element_html_class})})

    return d
示例#8
0
def append_edit_and_delete_links_to_field(form_element_plugin, \
                                          form_element_entry, origin=None, \
                                          extra={}, widget_cls=None):
    """
    Should return dictionary, which would be used to update default kwargs
    of form fields.

    The hidden inputs `form-{counter}-position` and `form-{counter}-id` are
    for saving the ordering of the elements (`position` field).

    :return dict:
    """
    theme = get_theme(as_instance=True)
    PluginForm = form_element_plugin.get_form()
    counter = extra.get('counter')
    edit_url = reverse(
        'fobi.edit_form_element_entry',
        kwargs = {'form_element_entry_id': form_element_entry.pk}
        )

    edit_option_html = theme.edit_form_entry_edit_option_html().format(
        edit_url = edit_url,
        edit_text = safe_text(ugettext("Edit")),
        )
    help_text_extra = theme.edit_form_entry_help_text_extra().format(
        edit_option_html = edit_option_html if PluginForm else '',
        delete_url = reverse('fobi.delete_form_element_entry', kwargs={'form_element_entry_id': form_element_entry.pk}),
        delete_text = safe_text(ugettext("Delete")),
        form_element_pk = form_element_entry.pk,
        form_element_position = form_element_entry.position,
        counter = counter
        )
    try:
        help_text = safe_text(form_element_plugin.data.help_text)
    except:
        help_text = ''

    d = {
        'help_text': "{0} {1}".format(help_text, help_text_extra),
    }

    label = safe_text(getattr(form_element_plugin.data, 'label', ''))
    d.update({'label': "{0} ({1})".format(label, safe_text(form_element_plugin.name))})

    #if 'hidden' == form_element_plugin.uid:
    #    d.update({'widget': TextInput(attrs={'class': theme.form_element_html_class})})
    if widget_cls:
        d.update({'widget': widget_cls(attrs={'class': theme.form_element_html_class})})
    elif form_element_plugin.is_hidden:
        d.update({'widget': TextInput(attrs={'class': theme.form_element_html_class})})

    return d
示例#9
0
    def run(self, form_entry, request, form, form_element_entries=None):
        """
        :param fobi.models.FormEntry form_entry: Instance of
            ``fobi.models.FormEntry``.
        :param django.http.HttpRequest request:
        :param django.forms.Form form:
        :param iterable form_element_entries: Iterable of
            ``fobi.models.FormElementEntry`` objects.
        """
        base_url = 'http{secure}://{host}'.format(
            secure = ('s' if request.is_secure() else ''),
            host = request.get_host()
            )

        # Clean up the values, leave our content fields and empty values.
        field_name_to_label_map, cleaned_data = get_processed_form_data(
            form,
            form_element_entries
            )

        rendered_data = []
        for key, value in cleaned_data.items():
            if value and isinstance(value, string_types) \
                     and value.startswith(settings.MEDIA_URL):
                cleaned_data[key] = '{base_url}{value}'.format(
                    base_url=base_url, value=value
                    )
            label = field_name_to_label_map.get(key, key)
            rendered_data.append('{0}: {1}\n'.format(
                safe_text(label), safe_text(cleaned_data[key]))
                )

        files = self._prepare_files(request, form)

        # Handling more than one email address
        if isinstance(self.data.to_email, (list, tuple)):
            to_email = self.data.to_email
        else:
            # Assume that it's string
            to_email = self.data.to_email.split(MULTI_EMAIL_FIELD_VALUE_SPLITTER)

        send_mail(
            safe_text(self.data.subject),
            "{0}\n\n{1}".format(safe_text(self.data.body),
            ''.join(rendered_data)),
            self.data.from_email,
            to_email,
            fail_silently = False,
            attachments = files.values()
            )
示例#10
0
    def submit_plugin_form_data(self, form_entry, request, form,
                                form_element_entries=None, **kwargs):
        """
        Submit plugin form data/process.

        :param fobi.models.FormEntry form_entry: Instance of
            ``fobi.models.FormEntry``.
        :param django.http.HttpRequest request:
        :param django.forms.Form form:
        """
        # In case if we should submit value as is, we don't return anything.
        # In other cases, we proceed further.

        # Get the object
        objs = form.cleaned_data.get(self.data.name, [])

        values = []

        for obj in objs:
            if obj:
                value = None
                # Should be returned as repr
                if SUBMIT_VALUE_AS == SUBMIT_VALUE_AS_REPR:
                    value = safe_text(obj)
                elif SUBMIT_VALUE_AS == SUBMIT_VALUE_AS_VAL:
                    value = '{0}.{1}.{2}'.format(
                        obj._meta.app_label,
                        get_model_name_for_object(obj),
                        obj.pk
                    )
                else:
                    # Handle the submitted form value
                    value = '{0}.{1}.{2}.{3}'.format(
                        obj._meta.app_label,
                        get_model_name_for_object(obj),
                        obj.pk,
                        safe_text(obj)
                    )
                values.append(value)

        # Overwrite ``cleaned_data`` of the ``form`` with object qualifier.
        if values:
            form.cleaned_data[self.data.name] = json.dumps(values)
        else:
            del form.cleaned_data[self.data.name]

        # It's critically important to return the ``form`` with updated
        # ``cleaned_data``
        return form
示例#11
0
def get_user_plugins(get_allowed_plugin_uids_func, get_registered_plugins_func,
                     registry, user):
    """
    Gets a list of user plugins in a form if tuple (plugin name, plugin
    description). If not yet autodiscovered, autodiscovers them.

    :param callable get_allowed_plugin_uids_func:
    :param callable get_registered_plugins_func:
    :param fobi.base.BaseRegistry registry: Subclass of
        ``fobi.base.BaseRegistry`` instance.
    :param django.contrib.auth.models.User user:
    :return list:
    """
    ensure_autodiscover()

    if not RESTRICT_PLUGIN_ACCESS or getattr(user, 'is_superuser', False):
        return get_registered_plugins_func()

    registered_plugins = []

    allowed_plugin_uids = get_allowed_plugin_uids_func(user)

    for uid, plugin in registry._registry.items():
        if uid in allowed_plugin_uids:
            plugin_name = safe_text(plugin.name)
            #if PY3:
            #    plugin_name = force_text(plugin.name, encoding='utf-8')
            #else:
            #    plugin_name = force_text(
            #        plugin.name, encoding='utf-8'
            #        ).encode('utf-8')
            registered_plugins.append((uid, plugin_name))

    return registered_plugins
示例#12
0
    def submit_plugin_form_data(self,
                                form_entry,
                                request,
                                form,
                                form_element_entries=None,
                                **kwargs):
        """Submit plugin form data/process.

        :param fobi.models.FormEntry form_entry: Instance of
            ``fobi.models.FormEntry``.
        :param django.http.HttpRequest request:
        :param django.forms.Form form:
        """
        # Get the object
        obj = form.cleaned_data.get(self.data.name, None)
        if obj:
            # Handle the submitted form value
            value = '{0}'.format(safe_text(obj))

            # Overwrite ``cleaned_data`` of the ``form`` with object qualifier.
            form.cleaned_data[self.data.name] = value

        # It's critically important to return the ``form`` with updated
        # ``cleaned_data``
        return form
示例#13
0
    def submit_plugin_form_data(self, form_entry, request, form):
        """
        Submit plugin form data/process.

        :param fobi.models.FormEntry form_entry: Instance of
            ``fobi.models.FormEntry``.
        :param django.http.HttpRequest request:
        :param django.forms.Form form:
        """
        # In case if we should submit value as is, we don't return anything.
        # In other cases, we proceed further.

        # Get the object
        obj = form.cleaned_data.get(self.data.name, None)
        if obj:
            value = None
            # Should be returned as repr
            if SUBMIT_VALUE_AS == SUBMIT_VALUE_AS_REPR:
                value = safe_text(obj)
            elif SUBMIT_VALUE_AS == SUBMIT_VALUE_AS_VAL:
                value = "{0}.{1}.{2}".format(obj._meta.app_label, obj._meta.module_name, obj.pk)
            else:
                # Handle the submitted form value
                value = "{0}.{1}.{2}.{3}".format(obj._meta.app_label, obj._meta.module_name, obj.pk, safe_text(obj))

            # Overwrite ``cleaned_data`` of the ``form`` with object qualifier.
            form.cleaned_data[self.data.name] = value

        # It's critically important to return the ``form`` with updated
        # ``cleaned_data``
        return form
示例#14
0
def get_user_plugins(get_allowed_plugin_uids_func, \
                     get_registered_plugins_func, registry, user):
    """
    Gets a list of user plugins in a form if tuple (plugin name, plugin
    description). If not yet autodiscovered, autodiscovers them.

    :param callable get_allowed_plugin_uids_func:
    :param callable get_registered_plugins_func:
    :param fobi.base.BaseRegistry registry: Subclass of
        ``fobi.base.BaseRegistry`` instance.
    :param django.contrib.auth.models.User user:
    :return list:
    """
    ensure_autodiscover()

    if not RESTRICT_PLUGIN_ACCESS or getattr(user, 'is_superuser', False):
        return get_registered_plugins_func()

    registered_plugins = []

    allowed_plugin_uids = get_allowed_plugin_uids_func(user)

    for uid, plugin in registry._registry.items():
        if uid in allowed_plugin_uids:
            plugin_name = safe_text(plugin.name)
            #if PY3:
            #    plugin_name = force_text(plugin.name, encoding='utf-8')
            #else:
            #    plugin_name = force_text(
            #        plugin.name, encoding='utf-8'
            #        ).encode('utf-8')
            registered_plugins.append((uid, plugin_name))

    return registered_plugins
示例#15
0
    def export_to_csv(self):
        """
        Export data to CSV.
        """
        #response = HttpResponse(mimetype="text/csv")
        response = self._get_initial_response(mimetype="text/csv")
        response['Content-Disposition'] = \
            'attachment; filename=db_store_export_data.csv'

        data_headers = self._get_data_headers()
        data_keys = data_headers.keys()
        data_values = data_headers.values()

        queue = StringIO()
        try:
            csv_obj = csv.writer(
                queue, delimiter=CSV_DELIMITER, quotechar=CSV_QUOTECHAR
                )
            writerow = csv_obj.writerow
        except TypeError:
            queue = BytesIO()
            delimiter = bytes(CSV_DELIMITER, encoding="utf-8")
            quotechar = bytes(CSV_QUOTECHAR, encoding="utf-8")
            csv_obj = csv.writer(
                queue, delimiter=delimiter, quotechar=quotechar
                )
            writerow = lambda row: csv.writerow(
                [safe_text(cell) for cell in row]
                )

        data_values = [safe_text(value) for value in data_values]

        writerow(data_values)

        for obj in self.queryset:
            data = json.loads(obj.saved_data)
            row_data = []
            for cell, key in enumerate(data_keys):
                row_data.append(data.get(key, ''))

            writerow(row_data)

        data = queue.getvalue()
        response.write(data)
        return response
示例#16
0
    def export_to_csv(self):
        """
        Export data to CSV.
        """
        #response = HttpResponse(mimetype="text/csv")
        response = self._get_initial_response(mimetype="text/csv")
        response['Content-Disposition'] = \
            'attachment; filename=db_store_export_data.csv'

        data_headers = self._get_data_headers()
        data_keys = data_headers.keys()
        data_values = data_headers.values()

        queue = StringIO()
        try:
            csv_obj = csv.writer(queue,
                                 delimiter=CSV_DELIMITER,
                                 quotechar=CSV_QUOTECHAR)
            writerow = csv_obj.writerow
        except TypeError:
            queue = BytesIO()
            delimiter = bytes(CSV_DELIMITER, encoding="utf-8")
            quotechar = bytes(CSV_QUOTECHAR, encoding="utf-8")
            csv_obj = csv.writer(queue,
                                 delimiter=delimiter,
                                 quotechar=quotechar)
            writerow = lambda row: csv.writerow(
                [safe_text(cell) for cell in row])

        data_values = [safe_text(value) for value in data_values]

        writerow(data_values)

        for obj in self.queryset:
            data = json.loads(obj.saved_data)
            row_data = []
            for cell, key in enumerate(data_keys):
                row_data.append(data.get(key, ''))

            writerow(row_data)

        data = queue.getvalue()
        response.write(data)
        return response
示例#17
0
    def get_form_field_instances(self):
        """
        Get form field instances.
        """
        kwargs = {"initial": "<p>{0}</p>".format(safe_text(ugettext("Dummy content"))), "required": False, "label": ""}

        form_field_instances = []

        form_field_instances.append((self.data.name, NoneField, kwargs))
        return form_field_instances
示例#18
0
    def plugin_data_repr(self):
        """Human readable representation of plugin data.

        :return string:
        """
        to_email = None
        # Handling more than one email address
        if isinstance(self.data.to_email, (list, tuple)):
            to_email = '{0} '.format(MULTI_EMAIL_FIELD_VALUE_SPLITTER).join(
                self.data.to_email)
        else:
            # Assume that it's string
            to_email = self.data.to_email

        context = {
            'to_name': safe_text(self.data.to_name),
            'to_email': to_email,
            'subject': safe_text(self.data.subject),
        }
        return render_to_string('mail/plugin_data_repr.html', context)
示例#19
0
    def get_form_field_instances(self, request=None, form_entry=None,
                                 form_element_entries=None, **kwargs):
        """Get form field instances."""
        field_kwargs = {
            'initial': "<p>{0}</p>".format(
                safe_text(ugettext("Dummy content"))
            ),
            'required': False,
            'label': '',
        }

        return[(self.data.name, NoneField, field_kwargs)]
示例#20
0
    def plugin_data_repr(self):
        """
        Human readable representation of plugin data.

        :return string:
        """
        to_email = None
        # Handling more than one email address
        if isinstance(self.data.to_email, (list, tuple)):
            to_email = '{0} '.format(MULTI_EMAIL_FIELD_VALUE_SPLITTER).join(
                            self.data.to_email
                            )
        else:
            # Assume that it's string
            to_email = self.data.to_email

        context = {
            'to_name': safe_text(self.data.to_name),
            'to_email': to_email,
            'subject': safe_text(self.data.subject),
        }
        return render_to_string('mail/plugin_data_repr.html', context)
示例#21
0
    def get_form_field_instances(self):
        """
        Get form field instances.
        """
        kwargs = {
            'initial': "<p>{0}</p>".format(safe_text(ugettext("Dummy content"))),
            'required': False,
            'label': '',
        }

        form_field_instances = []

        form_field_instances.append((self.data.name, NoneField, kwargs))
        return form_field_instances
示例#22
0
    def get_form_field_instances(self,
                                 request=None,
                                 form_entry=None,
                                 form_element_entries=None,
                                 **kwargs):
        """Get form field instances."""
        field_kwargs = {
            'initial':
            "<p>{0}</p>".format(safe_text(ugettext("Dummy content"))),
            'required': False,
            'label': '',
        }

        return [(self.data.name, NoneField, field_kwargs)]
示例#23
0
    def get_form_field_instances(self, request=None):
        """
        Get form field instances.
        """
        kwargs = {
            'initial': "<p>{0}</p>".format(safe_text(ugettext("Dummy content"))),
            'required': False,
            'label': '',
        }

        form_field_instances = []

        form_field_instances.append((self.data.name, NoneField, kwargs))
        return form_field_instances
示例#24
0
    def prepare_plugin_form_data(self, cleaned_data):
        """Prepare plugin form data.

        Might be used in integration plugins.
        """
        # In case if we should submit value as is, we don't return anything.
        # In other cases, we proceed further.

        # Get the object
        obj = cleaned_data.get(self.data.name, None)
        if obj:
            value = None
            # Should be returned as repr
            if SUBMIT_VALUE_AS == SUBMIT_VALUE_AS_REPR:
                value = safe_text(obj)
            elif SUBMIT_VALUE_AS == SUBMIT_VALUE_AS_VAL:
                value = '{0}.{1}.{2}'.format(
                    obj._meta.app_label,
                    get_model_name_for_object(obj),
                    obj.pk
                )
            else:
                # Handle the submitted form value
                value = '{0}.{1}.{2}.{3}'.format(
                    obj._meta.app_label,
                    get_model_name_for_object(obj),
                    obj.pk,
                    safe_text(obj)
                )

            # Overwrite ``cleaned_data`` of the ``form`` with object
            # qualifier.
            cleaned_data[self.data.name] = value

            # It's critically important to return the ``form`` with updated
            # ``cleaned_data``
            return cleaned_data
示例#25
0
    def submit_plugin_form_data(self,
                                form_entry,
                                request,
                                form,
                                form_element_entries=None,
                                **kwargs):
        """
        Submit plugin form data/process.

        :param fobi.models.FormEntry form_entry: Instance of
            ``fobi.models.FormEntry``.
        :param django.http.HttpRequest request:
        :param django.forms.Form form:
        """
        # In case if we should submit value as is, we don't return anything.
        # In other cases, we proceed further.
        if SUBMIT_VALUE_AS != SUBMIT_VALUE_AS_VAL:
            # Get the object
            values = form.cleaned_data.get(self.data.name, None)

            # Get choices
            choices = dict(get_select_field_choices(self.data.choices))

            # Returned value
            ret_values = []

            for value in values:
                # Handle the submitted form value

                if value in choices:
                    label = safe_text(choices.get(value))

                    # Should be returned as repr
                    if SUBMIT_VALUE_AS == SUBMIT_VALUE_AS_REPR:
                        value = label
                    # Should be returned as mix
                    else:
                        value = "{0} ({1})".format(label, value)

                    ret_values.append(value)

            # Overwrite ``cleaned_data`` of the ``form`` with object
            # qualifier.
            if ret_values:
                form.cleaned_data[self.data.name] = ret_values

            # It's critically important to return the ``form`` with updated
            # ``cleaned_data``
            return form
示例#26
0
    def render(self, name, value, attrs=None, **kwargs):
        if value is None:
            value = ''

        if not attrs:
            attrs = self.attrs
        else:
            attrs.update(self.attrs)

        final_attrs = self.build_attrs(attrs, extra_attrs={'name': name})

        return format_html(
            '<div class="markdown-widget-wrapper">'
            '<textarea{}>\r\n{}</textarea>'
            '<div class="markdown-preview">Preview</div>'
            '</div>', flatatt(final_attrs), safe_text(value))
示例#27
0
    def submit_plugin_form_data(self,
                                form_entry,
                                request,
                                form,
                                form_element_entries=None,
                                **kwargs):
        """Submit plugin form data/process.

        :param fobi.models.FormEntry form_entry: Instance of
            ``fobi.models.FormEntry``.
        :param django.http.HttpRequest request:
        :param django.forms.Form form:
        """
        # In case if we should submit value as is, we don't return anything.
        # In other cases, we proceed further.
        if SUBMIT_VALUE_AS != SUBMIT_VALUE_AS_VAL:
            # Get the object
            values = form.cleaned_data.get(self.data.name, None)

            # Get choices
            choices = dict(get_select_field_choices(self.data.choices))

            # Returned value
            ret_values = []

            for value in values:
                # Handle the submitted form value

                if value in choices:
                    label = safe_text(choices.get(value))

                    # Should be returned as repr
                    if SUBMIT_VALUE_AS == SUBMIT_VALUE_AS_REPR:
                        value = label
                    # Should be returned as mix
                    else:
                        value = "{0} ({1})".format(label, value)

                    ret_values.append(value)

            # Overwrite ``cleaned_data`` of the ``form`` with object
            # qualifier.
            form.cleaned_data[self.data.name] = ret_values

            # It's critically important to return the ``form`` with updated
            # ``cleaned_data``
            return form
示例#28
0
def get_user_form_handler_plugins(user,
                                  exclude_used_singles=False,
                                  used_form_handler_plugin_uids=[]):
    """
    Get list of plugins allowed for user.

    :param django.contrib.auth.models.User user:
    :param bool exclude_used_singles:
    :param list used_form_handler_plugin_uids:
    :return list:
    """
    user_form_handler_plugins = get_user_plugins(
        get_allowed_form_handler_plugin_uids,
        get_registered_form_handler_plugins,
        form_handler_plugin_registry,
        user
    )
    user_form_handler_plugin_uids = [plugin_uid
                                     for (plugin_uid, plugin_name)
                                     in user_form_handler_plugins]

    if exclude_used_singles and used_form_handler_plugin_uids:
        # Get all registered form handler plugins (as instances)
        registered_form_handler_plugins = \
            get_registered_form_handler_plugins(as_instances=True)

        # Check if we need to reduce the list of allowed plugins if they have
        # been marked to be used once per form and have been used already in
        # the current form.
        for plugin_uid, plugin \
            in registered_form_handler_plugins.items():

            if plugin.uid in user_form_handler_plugin_uids \
               and not plugin.allow_multiple \
               and plugin.uid in used_form_handler_plugin_uids:

                # Remove the plugin so that we don't get links to add it
                # in the UI.
                plugin_name = safe_text(plugin.name)
                user_form_handler_plugins.remove(
                    (plugin.uid, plugin_name)
                )

    return user_form_handler_plugins
    def submit_plugin_form_data(self, form_entry, request, form,
                                form_element_entries=None, **kwargs):
        """Submit plugin form data/process.

        :param fobi.models.FormEntry form_entry: Instance of
            ``fobi.models.FormEntry``.
        :param django.http.HttpRequest request:
        :param django.forms.Form form:
        """
        # Get the object
        obj = form.cleaned_data.get(self.data.name, None)
        if obj:
            # Handle the submitted form value
            value = '{0}'.format(safe_text(obj))

            # Overwrite ``cleaned_data`` of the ``form`` with object qualifier.
            form.cleaned_data[self.data.name] = value

        # It's critically important to return the ``form`` with updated
        # ``cleaned_data``
        return form
示例#30
0
def get_user_form_handler_plugins(user,
                                  exclude_used_singles=False,
                                  used_form_handler_plugin_uids=[]):
    """
    Get list of plugins allowed for user.

    :param django.contrib.auth.models.User user:
    :param bool exclude_used_singles:
    :param list used_form_handler_plugin_uids:
    :return list:
    """
    user_form_handler_plugins = get_user_plugins(
        get_allowed_form_handler_plugin_uids,
        get_registered_form_handler_plugins, form_handler_plugin_registry,
        user)
    user_form_handler_plugin_uids = [
        plugin_uid for (plugin_uid, plugin_name) in user_form_handler_plugins
    ]

    if exclude_used_singles and used_form_handler_plugin_uids:
        # Get all registered form handler plugins (as instances)
        registered_form_handler_plugins = \
            get_registered_form_handler_plugins(as_instances=True)

        # Check if we need to reduce the list of allowed plugins if they have
        # been marked to be used once per form and have been used already in
        # the current form.
        for plugin_uid, plugin \
            in registered_form_handler_plugins.items():

            if plugin.uid in user_form_handler_plugin_uids \
               and not plugin.allow_multiple \
               and plugin.uid in used_form_handler_plugin_uids:

                # Remove the plugin so that we don't get links to add it
                # in the UI.
                plugin_name = safe_text(plugin.name)
                user_form_handler_plugins.remove((plugin.uid, plugin_name))

    return user_form_handler_plugins
示例#31
0
    def submit_plugin_form_data(self, form_entry, request, form):
        """Submit plugin form data/process.

        :param fobi.models.FormEntry form_entry: Instance of
            ``fobi.models.FormEntry``.
        :param django.http.HttpRequest request:
        :param django.forms.Form form:
        """
        # Get the object
        value = form.cleaned_data.get(self.data.name, None)

        if value:
            choices = dict(get_select_field_choices(self.data.choices))
            # Handle the submitted form value
            value = '{0}'.format(safe_text(choices.get(value)))

            # Overwrite ``cleaned_data`` of the ``form`` with object qualifier.
            form.cleaned_data[self.data.name] = value

        # It's critically important to return the ``form`` with updated
        # ``cleaned_data``
        return form
示例#32
0
    def prepare_plugin_form_data(self, cleaned_data):
        """Prepare plugin form data.

        Might be used in integration plugins.
        """
        # In case if we should submit value as is, we don't return anything.
        # In other cases, we proceed further.
        if SUBMIT_VALUE_AS != SUBMIT_VALUE_AS_VAL:
            # Get the object
            values = cleaned_data.get(self.data.name, None)

            # Get choices
            choices = dict(self.get_choices())

            # Returned value
            ret_values = []

            for value in values:
                # Handle the submitted form value

                if value in choices:
                    label = safe_text(choices.get(value))

                    # Should be returned as repr
                    if SUBMIT_VALUE_AS == SUBMIT_VALUE_AS_REPR:
                        value = label
                    # Should be returned as mix
                    else:
                        value = "{0} ({1})".format(label, value)

                    ret_values.append(value)

            # Overwrite ``cleaned_data`` of the ``form`` with object
            # qualifier.
            cleaned_data[self.data.name] = ret_values

            # It's critically important to return the ``form`` with updated
            # ``cleaned_data``
            return cleaned_data
示例#33
0
    def submit_plugin_form_data(self, form_entry, request, form):
        """
        Submit plugin form data/process.

        :param fobi.models.FormEntry form_entry: Instance of
            ``fobi.models.FormEntry``.
        :param django.http.HttpRequest request:
        :param django.forms.Form form:
        """
        # Get the object
        value = form.cleaned_data.get(self.data.name, None)

        if value:
            choices = dict(get_select_field_choices(self.data.choices))
            # Handle the submitted form value
            value = '{0}'.format(safe_text(choices.get(value)))

            # Overwrite ``cleaned_data`` of the ``form`` with object qualifier.
            form.cleaned_data[self.data.name] = value

        # It's critically important to return the ``form`` with updated
        # ``cleaned_data``
        return form
示例#34
0
    def render(self, name, value, attrs=None, **kwargs):
        if value is None:
            value = ''

        if not attrs:
            attrs = self.attrs
        else:
            attrs.update(self.attrs)

        if DJANGO_GTE_1_11:
            final_attrs = self.build_attrs(
                attrs,
                extra_attrs={'name': name}
            )
        else:
            final_attrs = self.build_attrs(attrs, name=name)
        return format_html(
            '<div class="markdown-widget-wrapper">'
            '<textarea{}>\r\n{}</textarea>'
            '<div class="markdown-preview">Preview</div>'
            '</div>',
            flatatt(final_attrs),
            safe_text(value)
        )
示例#35
0
 def writerow(row):
     """Write row."""
     return csv.writerow([safe_text(__cell) for __cell in row])