Exemple #1
0
def dashboard(request, theme=None, template_name=None):
    """
    Dashboard.

    :param django.http.HttpRequest request:
    :param string template_name:
    :return django.http.HttpResponse:
    """
    form_entries = FormEntry._default_manager \
                            .filter(user__pk=request.user.pk) \
                            .select_related('user')

    context = {'form_entries': form_entries}

    # 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:
        theme = get_theme(request=request, as_instance=True)
        template_name = theme.dashboard_template

    return render_to_response(
        template_name, context, context_instance=RequestContext(request)
        )
Exemple #2
0
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        if self.request is None:
            raise ImproperlyConfigured(
                ugettext("The {0} form requires a "
                         "request argument.".format(self.__class__.__name__))
                )

        super(FormEntryForm, self).__init__(*args, **kwargs)
        theme = get_theme(request=None, as_instance=True)

        self.fields['name'].widget = forms.widgets.TextInput(
            attrs={'class': theme.form_element_html_class}
            )

        self.fields['success_page_title'].widget = forms.widgets.TextInput(
            attrs={'class': theme.form_element_html_class}
            )

        self.fields['success_page_message'].widget = forms.widgets.Textarea(
            attrs={'class': theme.form_element_html_class}
            )

        self.fields['action'].widget = forms.widgets.TextInput(
            attrs={'class': theme.form_element_html_class}
            )

        # At the moment this is done for Foundation 5 theme. Remove this once
        # it's possible for a theme to override this form. Alternatively, add
        # the attrs to the theme API.
        self.fields['is_public'].widget = forms.widgets.CheckboxInput(
            attrs={'data-customforms': 'disabled'}
            )
Exemple #3
0
    def __init__(self, *args, **kwargs):
        super(FormEntryForm, self).__init__(*args, **kwargs)
        theme = get_theme(request=None, as_instance=True)

        self.fields['name'].widget = forms.widgets.TextInput(
            attrs={'class': theme.form_element_html_class}
            )

        self.fields['success_page_title'].widget = forms.widgets.TextInput(
            attrs={'class': theme.form_element_html_class}
            )

        self.fields['success_page_message'].widget = forms.widgets.Textarea(
            attrs={'class': theme.form_element_html_class}
            )

        self.fields['action'].widget = forms.widgets.TextInput(
            attrs={'class': theme.form_element_html_class}
            )

        # At the moment this is done for Foundation 5 theme. Remove this once
        # it's possible for a theme to override this form. Alternatively, add
        # the attrs to the theme API.
        self.fields['is_public'].widget = forms.widgets.CheckboxInput(
            attrs={'data-customforms': 'disabled'}
            )
Exemple #4
0
def forms_list(request, template_name='foo/forms_list.html'):
    """Fobi forms list.

    :param django.http.HttpRequest request:
    :param string template_name:
    :return django.http.HttpResponse:
    """
    form_entries = FormEntry._default_manager.filter(is_public=True) \
                                             .select_related('user')
    theme = get_theme(request=request, as_instance=True)
    context = {
        'form_entries': form_entries,
        'theme': theme,
        'show_custom_actions': False,
        'show_edit_link': False,
        'show_delete_link': False,
        'show_export_link': False,
    }

    if versions.DJANGO_GTE_1_10:
        return render(request, template_name, context)
    else:
        return render_to_response(
            template_name, context, context_instance=RequestContext(request)
        )
Exemple #5
0
    def _show_thanks_page(self, request, instance, **kwargs):
        """
        Renders the thanks page after successful form submission.

        :param django.http.HttpRequest request:
        :param fobi.models.FormEntry instance: FormEntry instance.
        :return str:
        """
        template_name = instance.success_page_template_name or None

        theme = get_theme(request=request, as_instance=True)

        context = {
            'form_entry': instance.form_entry,
            'fobi_theme': theme,
            'fobi_hide_success_page_title': instance.hide_success_page_title,
            'fobi_success_page_title': instance.success_page_title,
            'fobi_success_page_text': instance.success_page_text,
        }

        if not template_name:
            template_name = theme.embed_form_entry_submitted_ajax_template

        self.rendered_output = render_to_string(
            template_name, context, context_instance=RequestContext(request)
            )
Exemple #6
0
def form_entry_submitted(request, form_entry_slug=None, template_name=None):
    """
    Form entry submitted.

    :param django.http.HttpRequest request:
    :param string form_entry_slug:
    :param string template_name:
    :return django.http.HttpResponse:
    """
    try:
        form_entry = FormEntry._default_manager.get(slug=form_entry_slug,
                                                    user__pk=request.user.pk)
    except ObjectDoesNotExist as err:
        raise Http404(ugettext("Form entry not found."))

    context = {
        'form_entry_slug': form_entry_slug,
        'form_entry': form_entry
    }

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

    return render_to_response(template_name, context,
                              context_instance=RequestContext(request))
Exemple #7
0
def get_template_choices(source, choices, theme_specific_choices_key):
    """
    Gets the template choices. It's possible to provide theme templates
    per theme or just per project.

    :param str source: Example value 'feincms_integration'.
    :param tuple or list choices:
    :param str theme_specific_choices_key:
    :return list:
    """
    template_choices = []
    if choices:
        #template_choices += [(None, _("--- General templates ---"))]
        #template_choices += (_("General templates"), list(FORM_TEMPLATE_CHOICES))
        template_choices += list(choices)

    theme = get_theme(as_instance=True)
    theme_template_choices = []
    try:
        theme_template_choices = list(
            theme.custom_data[source][theme_specific_choices_key]
            )
        #template_choices += [(None, _("--- Theme templates ---"))]
        #template_choices += (_("Theme templates"), theme_template_choices)
        template_choices += theme_template_choices
    except KeyError:
        pass

    return template_choices
Exemple #8
0
def form_entry_submitted(request, form_entry_slug=None, template_name=None):
    """
    Form entry submitted.

    :param django.http.HttpRequest request:
    :param string form_entry_slug:
    :param string template_name:
    :return django.http.HttpResponse:
    """
    try:
        kwargs = {'slug': form_entry_slug}
        if not request.user.is_authenticated():
            kwargs.update({'is_public': True})
        form_entry = FormEntry._default_manager.select_related('user') \
                               .get(**kwargs)
    except ObjectDoesNotExist as err:
        raise Http404(ugettext("Form entry not found."))

    # try:
    #     form_entry = FormEntry._default_manager.get(slug=form_entry_slug,
    #                                                 user__pk=request.user.pk)
    # except ObjectDoesNotExist as err:
    #     raise Http404(ugettext("Form entry not found."))

    context = {
        'form_entry_slug': form_entry_slug,
        'form_entry': form_entry
    }

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

    return render_to_response(template_name, context,
                              context_instance=RequestContext(request))
Exemple #9
0
def theme(request):
    """
    Gets active theme.

    :param django.http.HttpRequest request:
    :return fobi.base.BaseTheme: Instance of ``fobi.base.BaseTheme``.
    """
    return {'fobi_theme': get_theme(request, as_instance=True)}
Exemple #10
0
def theme(request):
    """
    Gets active theme.

    :param django.http.HttpRequest request:
    :return fobi.base.BaseTheme: Instance of ``fobi.base.BaseTheme``.
    """
    return {'fobi_theme': get_theme(request, as_instance=True)}
Exemple #11
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
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
Exemple #13
0
def forms_list(request, template_name="foo/forms_list.html"):
    """
    Fobi forms list.
    """
    form_entries = FormEntry._default_manager.filter(is_public=True).select_related("user")
    theme = get_theme(request=request, as_instance=True)
    context = {
        "form_entries": form_entries,
        "theme": theme,
        "show_custom_actions": False,
        "show_edit_link": False,
        "show_delete_link": False,
        "show_export_link": False,
    }
    return render_to_response(template_name, context, context_instance=RequestContext(request))
Exemple #14
0
def create_form_entry(request, theme=None, template_name=None):
    """
    :param django.http.HttpRequest request:
    :return django.http.HttpResponse:
    """
    if 'POST' == request.method:
        form = FormEntryForm(request.POST, request.FILES, request=request)
        if form.is_valid():
            form_entry = form.save(commit=False)
            form_entry.user = request.user
            try:
                form_entry.save()
                messages.info(
                    request,
                    _('Form {0} was created successfully.').format(
                        form_entry.name
                        )
                    )
                return redirect(
                    'fobi.edit_form_entry', form_entry_id=form_entry.pk
                    )
            except IntegrityError as err:
                messages.info(
                    request,
                    _('Errors occured while saving the form: {0}.').format(
                        str(err)
                        )
                    )

    else:
        form = FormEntryForm(request=request)

    context = {'form': form}

    # 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.create_form_entry_template

    return render_to_response(
        template_name, context, context_instance=RequestContext(request)
        )
Exemple #15
0
def forms_list(request, template_name='foo/forms_list.html'):
    """
    Fobi forms list.
    """
    form_entries = FormEntry._default_manager.filter(is_public=True) \
                                             .select_related('user')
    theme = get_theme(request=request, as_instance=True)
    context = {
        'form_entries': form_entries,
        'theme': theme,
        'show_custom_actions': False,
        'show_edit_link': False,
        'show_delete_link': False,
        'show_export_link': False,
    }
    return render_to_response(
        template_name, context, context_instance=RequestContext(request)
    )
Exemple #16
0
def create_form_entry(request, theme=None, template_name=None):
    """
    :param django.http.HttpRequest request:
    :param fobi.base.BaseTheme theme: Theme instance.
    :param str template_name:
    :return django.http.HttpResponse:
    """
    if 'POST' == request.method:
        form = FormEntryForm(request.POST, request.FILES, request=request)
        if form.is_valid():
            form_entry = form.save(commit=False)
            form_entry.user = request.user
            try:
                form_entry.save()
                messages.info(
                    request,
                    _('Form {0} was created '
                      'successfully.').format(form_entry.name))
                return redirect('fobi.edit_form_entry',
                                form_entry_id=form_entry.pk)
            except IntegrityError as err:
                messages.info(
                    request,
                    _('Errors occured while saving '
                      'the form: {0}.').format(str(err)))

    else:
        form = FormEntryForm(request=request)

    context = {'form': form}

    # 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.create_form_entry_template

    return render_to_response(template_name,
                              context,
                              context_instance=RequestContext(request))
Exemple #17
0
def forms_list(request, template_name='foo/forms_list.html'):
    """Fobi forms list.

    :param django.http.HttpRequest request:
    :param string template_name:
    :return django.http.HttpResponse:
    """
    form_entries = FormEntry._default_manager.filter(is_public=True) \
                                             .select_related('user')
    theme = get_theme(request=request, as_instance=True)
    context = {
        'form_entries': form_entries,
        'theme': theme,
        'show_custom_actions': False,
        'show_edit_link': False,
        'show_delete_link': False,
        'show_export_link': False,
    }

    return render(request, template_name, context)
Exemple #18
0
    def __init__(self, *args, **kwargs):
        super(FormEntryForm, self).__init__(*args, **kwargs)
        theme = get_theme(request=None, as_instance=True)

        self.fields['name'].widget = forms.widgets.TextInput(
            attrs={'class': theme.form_element_html_class})

        self.fields['success_page_title'].widget = forms.widgets.TextInput(
            attrs={'class': theme.form_element_html_class})

        self.fields['success_page_message'].widget = forms.widgets.Textarea(
            attrs={'class': theme.form_element_html_class})

        self.fields['action'].widget = forms.widgets.TextInput(
            attrs={'class': theme.form_element_html_class})

        # At the moment this is done for Foundation 5 theme. Remove this once
        # it's possible for a theme to override this form. Alternatively, add
        # the attrs to the theme API.
        self.fields['is_public'].widget = forms.widgets.CheckboxInput(
            attrs={'data-customforms': 'disabled'})
Exemple #19
0
def edit_form_handler_entry(request,
                            form_handler_entry_id,
                            theme=None,
                            template_name=None):
    """
    Edit form handler entry.

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

    form_entry = obj.form_entry

    form_handler_plugin = obj.get_plugin(request=request)
    form_handler_plugin.request = request

    FormHandlerPluginForm = form_handler_plugin.get_form()
    form = None

    if not FormHandlerPluginForm:
        messages.info(
            request,
            _('The form handler plugin "{0}" is not '
              'configurable!').format(form_handler_plugin.name))
        return redirect('fobi.edit_form_entry', form_entry_id=form_entry.pk)

    elif 'POST' == request.method:
        form = form_handler_plugin.get_initialised_edit_form_or_404(
            data=request.POST, files=request.FILES)

        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 the object.
            obj.save()

            messages.info(
                request,
                _('The form handler plugin "{0}" was edited '
                  'successfully.').format(form_handler_plugin.name))

            return redirect('fobi.edit_form_entry',
                            form_entry_id=form_entry.pk)

    else:
        form = form_handler_plugin.get_initialised_edit_form_or_404()

    context = {
        'form': form,
        'form_entry': form_entry,
        'form_handler_plugin': form_handler_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.edit_form_handler_entry_template

    return render_to_response(template_name,
                              context,
                              context_instance=RequestContext(request))
Exemple #20
0
def add_form_handler_entry(request,
                           form_entry_id,
                           form_handler_plugin_uid,
                           theme=None,
                           template_name=None):
    """
    Add form handler entry.

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

    user_form_handler_plugin_uids = get_user_form_handler_plugin_uids(
        request.user)

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

    FormHandlerPlugin = form_handler_plugin_registry.get(
        form_handler_plugin_uid)

    # Check if we deal with form handler plugin that is only allowed to be
    # used once. In that case, check if it has been used already in the current
    # form entry.
    if not FormHandlerPlugin.allow_multiple:
        times_used = FormHandlerEntry._default_manager \
                                     .filter(form_entry__id=form_entry_id,
                                             plugin_uid=FormHandlerPlugin.uid) \
                                     .count()
        if times_used > 0:
            raise Http404(
                ugettext("The {0} plugin can be used only once in a "
                         "form.").format(FormHandlerPlugin.name))

    form_handler_plugin = FormHandlerPlugin(user=request.user)
    form_handler_plugin.request = request

    FormHandlerPluginForm = form_handler_plugin.get_form()
    form = None

    obj = FormHandlerEntry()
    obj.form_entry = form_entry
    obj.plugin_uid = form_handler_plugin_uid
    obj.user = request.user

    save_object = False

    if not FormHandlerPluginForm:
        save_object = True

    elif 'POST' == request.method:
        form = form_handler_plugin.get_initialised_create_form_or_404(
            data=request.POST, files=request.FILES)
        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

    else:
        form = form_handler_plugin.get_initialised_create_form_or_404()

    if save_object:
        # Save the object.
        obj.save()

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

    context = {
        'form': form,
        'form_entry': form_entry,
        'form_handler_plugin': form_handler_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_handler_entry_template

    return render_to_response(template_name,
                              context,
                              context_instance=RequestContext(request))
Exemple #21
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))
Exemple #22
0
def edit_form_entry(request, form_entry_id, theme=None, template_name=None):
    """
    Edit form entry.

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

    if 'POST' == request.method:
        # The form entry form (does not contain form elenments)
        form = FormEntryForm(request.POST,
                             request.FILES,
                             instance=form_entry,
                             request=request)

        if 'ordering' in request.POST:
            form_element_entry_formset = FormElementEntryFormSet(
                request.POST,
                request.FILES,
                queryset=form_entry.formelemententry_set.all(),
                #prefix = 'form_element'
            )
            # If form elements aren't properly made (developers's fault)
            # there might be problems with saving the ordering - likely
            # in case of hidden elements only. Thus, we want to avoid
            # errors here.
            try:
                if form_element_entry_formset.is_valid():
                    form_element_entry_formset.save()
                    messages.info(request,
                                  _("Elements ordering edited successfully."))
                    return redirect(
                        reverse('fobi.edit_form_entry',
                                kwargs={'form_entry_id': form_entry_id}))
            except MultiValueDictKeyError as err:
                messages.error(
                    request,
                    _("Errors occured while trying to change the "
                      "elements ordering!"))
                return redirect(
                    reverse('fobi.edit_form_entry',
                            kwargs={'form_entry_id': form_entry_id}))
        else:
            form_element_entry_formset = FormElementEntryFormSet(
                queryset=form_entry.formelemententry_set.all(),
                #prefix = 'form_element'
            )

        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            try:
                obj.save()
                messages.info(
                    request,
                    _('Form {0} was edited '
                      'successfully.').format(form_entry.name))
                return redirect(
                    reverse('fobi.edit_form_entry',
                            kwargs={'form_entry_id': form_entry_id}))
            except IntegrityError as err:
                messages.info(
                    request,
                    _('Errors occured while saving '
                      'the form: {0}.').format(str(err)))
    else:
        # The form entry form (does not contain form elenments)
        form = FormEntryForm(instance=form_entry, request=request)

        form_element_entry_formset = FormElementEntryFormSet(
            queryset=form_entry.formelemententry_set.all(),
            #prefix = 'form_element'
        )

    # In case of success, we don't need this (since redirect would happen).
    # Thus, fetch only if needed.
    form_elements = form_entry.formelemententry_set.all()
    form_handlers = form_entry.formhandlerentry_set.all()[:]
    used_form_handler_uids = [form_handler.plugin_uid for form_handler \
                                                      in form_handlers]
    all_form_entries = FormEntry._default_manager.only('id', 'name', 'slug') \
                                .filter(user__pk=request.user.pk)

    # List of form element plugins allowed to user
    user_form_element_plugins = get_user_form_element_plugins_grouped(
        request.user)
    # List of form handler plugins allowed to user
    user_form_handler_plugins = get_user_form_handler_plugins(
        request.user,
        exclude_used_singles=True,
        used_form_handler_plugin_uids=used_form_handler_uids)

    # Assembling the form for preview
    FormClass = assemble_form_class(
        form_entry,
        origin='edit_form_entry',
        origin_kwargs_update_func=append_edit_and_delete_links_to_field,
        request=request)

    assembled_form = FormClass()

    # In debug mode, try to identify possible problems.
    if DEBUG:
        try:
            assembled_form.as_p()
        except Exception as err:
            logger.error(err)

    # If no theme provided, pick a default one.
    if not theme:
        theme = get_theme(request=request, as_instance=True)

    theme.collect_plugin_media(form_elements)

    context = {
        'form': form,
        'form_entry': form_entry,
        'form_elements': form_elements,
        'form_handlers': form_handlers,
        'all_form_entries': all_form_entries,
        'user_form_element_plugins': user_form_element_plugins,
        'user_form_handler_plugins': user_form_handler_plugins,
        'assembled_form': assembled_form,
        'form_element_entry_formset': form_element_entry_formset,
        'fobi_theme': theme,
    }

    if not template_name:
        template_name = theme.edit_form_entry_template

    return render_to_response(template_name,
                              context,
                              context_instance=RequestContext(request))
Exemple #23
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))
Exemple #24
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))
Exemple #25
0
    def _process_form(self, request, instance, **kwargs):
        """
        Handle the form if no "sent" GET argument (see the
        ``WIDGET_FORM_SENT_GET_PARAM`` setting).

        :param django.http.HttpRequest request:
        :param fobi.models.FormEntry instance: FormEntry instance.
        :return django.http.HttpResponse | str:
        """
        template_name = instance.form_template_name or None

        # Handle public/non-public forms. If form requires user authentication
        # redirect to login form with next parameter set to current request
        # path.
        if not request.user.is_authenticated() and not instance.form_entry.is_public:
            if self.can_redirect:
                return redirect(
                    "{0}?next={1}".format(settings.LOGIN_URL, request.path)
                    )
            else:
                return self._show_login_required_page(
                    request, instance, **kwargs
                    )

        form_element_entries = instance.form_entry.formelemententry_set.all()[:]
        # This is where the most of the magic happens. Our form is being built
        # dynamically.
        FormClass = assemble_form_class(
            instance.form_entry,
            form_element_entries = form_element_entries
            )

        if 'POST' == request.method:
            form = FormClass(request.POST, request.FILES)

            # Fire pre form validation callbacks
            fire_form_callbacks(
                form_entry = instance.form_entry,
                request = request,
                form = form,
                stage = CALLBACK_BEFORE_FORM_VALIDATION)

            if form.is_valid():
                # Fire form valid callbacks, before handling sufrom
                # django.http import HttpResponseRedirectbmitted plugin
                # form data
                form = fire_form_callbacks(
                    form_entry = instance.form_entry,
                    request = request,
                    form = form,
                    stage = CALLBACK_FORM_VALID_BEFORE_SUBMIT_PLUGIN_FORM_DATA
                    )

                # Fire plugin processors
                form = submit_plugin_form_data(
                    form_entry = instance.form_entry,
                    request = request,
                    form = form
                    )

                # Fire form valid callbacks
                form = fire_form_callbacks(
                    form_entry = instance.form_entry,
                    request = request,
                    form = form,
                    stage = CALLBACK_FORM_VALID
                    )

                # Run all handlers
                run_form_handlers(
                    form_entry = instance.form_entry,
                    request = request,
                    form = form
                    )

                # Fire post handler callbacks
                fire_form_callbacks(
                    form_entry = instance.form_entry,
                    request = request,
                    form = form,
                    stage = CALLBACK_FORM_VALID_AFTER_FORM_HANDLERS
                    )

                messages.info(
                    request,
                    _('Form {0} was submitted '
                      'successfully.').format(instance.form_entry.name)
                    )

                if self.can_redirect:
                    return redirect(
                        "{0}?{1}={2}".format(request.path, \
                                             self.form_sent_get_param, \
                                             instance.form_entry.slug)
                        )
                else:
                    return self._show_thanks_page(request, instance, **kwargs)

            else:
                # Fire post form validation callbacks
                fire_form_callbacks(
                    form_entry = instance.form_entry,
                    request = request,
                    form = form,
                    stage = CALLBACK_FORM_INVALID
                    )

        else:
            # Providing initial form data by feeding entire GET dictionary
            # to the form, if ``GET_PARAM_INITIAL_DATA`` is present in the
            # GET.
            kwargs = {}
            if GET_PARAM_INITIAL_DATA in request.GET:
                kwargs = {'initial': request.GET}
            form = FormClass(**kwargs)

        theme = get_theme(request=request, as_instance=True)
        theme.collect_plugin_media(form_element_entries)

        context = {
            'form': form,
            'form_entry': instance.form_entry,
            'fobi_theme': theme,
            'fobi_form_title': instance.form_title,
            'fobi_hide_form_title': instance.hide_form_title,
            'fobi_form_submit_button_text': instance.form_submit_button_text
        }

        if not template_name:
            template_name = theme.view_embed_form_entry_ajax_template

        self.rendered_output = render_to_string(
            template_name, context, context_instance=RequestContext(request)
            )
Exemple #26
0
def view_form_entry(request, form_entry_slug, theme=None, template_name=None):
    """
    View create form.

    :param django.http.HttpRequest request:
    :param string form_entry_slug:
    :param fobi.base.BaseTheme theme: Theme instance.
    :param string template_name:
    :return django.http.HttpResponse:
    """
    try:
        kwargs = {'slug': form_entry_slug}
        if not request.user.is_authenticated():
            kwargs.update({'is_public': True})
        form_entry = FormEntry._default_manager.select_related('user') \
                              .get(**kwargs)
    except ObjectDoesNotExist as err:
        raise Http404(ugettext("Form entry not found."))

    form_element_entries = form_entry.formelemententry_set.all()[:]

    # This is where the most of the magic happens. Our form is being built
    # dynamically.
    FormClass = assemble_form_class(form_entry,
                                    form_element_entries=form_element_entries,
                                    request=request)

    if 'POST' == request.method:
        form = FormClass(request.POST, request.FILES)

        # Fire pre form validation callbacks
        fire_form_callbacks(form_entry=form_entry,
                            request=request,
                            form=form,
                            stage=CALLBACK_BEFORE_FORM_VALIDATION)

        if form.is_valid():
            # Fire form valid callbacks, before handling submitted plugin
            # form data.
            form = fire_form_callbacks(
                form_entry=form_entry,
                request=request,
                form=form,
                stage=CALLBACK_FORM_VALID_BEFORE_SUBMIT_PLUGIN_FORM_DATA)

            # Fire plugin processors
            form = submit_plugin_form_data(form_entry=form_entry,
                                           request=request,
                                           form=form)

            # Fire form valid callbacks
            form = fire_form_callbacks(form_entry=form_entry,
                                       request=request,
                                       form=form,
                                       stage=CALLBACK_FORM_VALID)

            # Run all handlers
            handler_responses, handler_errors = run_form_handlers(
                form_entry=form_entry,
                request=request,
                form=form,
                form_element_entries=form_element_entries)

            # Warning that not everything went ok.
            if handler_errors:
                for handler_error in handler_errors:
                    messages.warning(
                        request,
                        _("Error occured: {0}."
                          "").format(handler_error))

            # Fire post handler callbacks
            fire_form_callbacks(form_entry=form_entry,
                                request=request,
                                form=form,
                                stage=CALLBACK_FORM_VALID_AFTER_FORM_HANDLERS)

            messages.info(
                request,
                _("Form {0} was submitted successfully."
                  "").format(form_entry.name))
            return redirect(
                reverse('fobi.form_entry_submitted', args=[form_entry.slug]))
        else:
            # Fire post form validation callbacks
            fire_form_callbacks(form_entry=form_entry,
                                request=request,
                                form=form,
                                stage=CALLBACK_FORM_INVALID)

    else:
        # Providing initial form data by feeding entire GET dictionary
        # to the form, if ``GET_PARAM_INITIAL_DATA`` is present in the
        # GET.
        kwargs = {}
        if GET_PARAM_INITIAL_DATA in request.GET:
            kwargs = {'initial': request.GET}
        form = FormClass(**kwargs)

    # In debug mode, try to identify possible problems.
    if DEBUG:
        try:
            form.as_p()
        except Exception as err:
            logger.error(err)

    theme = get_theme(request=request, as_instance=True)
    theme.collect_plugin_media(form_element_entries)

    context = {
        'form': form,
        'form_entry': form_entry,
        'fobi_theme': theme,
    }

    if not template_name:
        template_name = theme.view_form_entry_template

    return render_to_response(template_name,
                              context,
                              context_instance=RequestContext(request))
Exemple #27
0
    def _process_form(self, request, instance, **kwargs):
        """
        Handle the form if no "sent" GET argument (see the
        ``WIDGET_FORM_SENT_GET_PARAM`` setting).

        :param django.http.HttpRequest request:
        :param fobi.models.FormEntry instance: FormEntry instance.
        :return django.http.HttpResponse | str:
        """
        template_name = instance.form_template_name or None

        # Handle public/non-public forms. If form requires user authentication
        # redirect to login form with next parameter set to current request
        # path.
        if not request.user.is_authenticated(
        ) and not instance.form_entry.is_public:
            if self.can_redirect:
                return redirect("{0}?next={1}".format(settings.LOGIN_URL,
                                                      request.path))
            else:
                return self._show_login_required_page(request, instance,
                                                      **kwargs)

        form_element_entries = instance.form_entry.formelemententry_set.all(
        )[:]
        # This is where the most of the magic happens. Our form is being built
        # dynamically.
        FormClass = assemble_form_class(
            instance.form_entry,
            form_element_entries=form_element_entries,
            request=request)

        if 'POST' == request.method:
            form = FormClass(request.POST, request.FILES)

            # Fire pre form validation callbacks
            fire_form_callbacks(form_entry=instance.form_entry,
                                request=request,
                                form=form,
                                stage=CALLBACK_BEFORE_FORM_VALIDATION)

            if form.is_valid():
                # Fire form valid callbacks, before handling sufrom
                # django.http import HttpResponseRedirectbmitted plugin
                # form data
                form = fire_form_callbacks(
                    form_entry=instance.form_entry,
                    request=request,
                    form=form,
                    stage=CALLBACK_FORM_VALID_BEFORE_SUBMIT_PLUGIN_FORM_DATA)

                # Fire plugin processors
                form = submit_plugin_form_data(form_entry=instance.form_entry,
                                               request=request,
                                               form=form)

                # Fire form valid callbacks
                form = fire_form_callbacks(form_entry=instance.form_entry,
                                           request=request,
                                           form=form,
                                           stage=CALLBACK_FORM_VALID)

                # Run all handlers
                run_form_handlers(form_entry=instance.form_entry,
                                  request=request,
                                  form=form)

                # Fire post handler callbacks
                fire_form_callbacks(
                    form_entry=instance.form_entry,
                    request=request,
                    form=form,
                    stage=CALLBACK_FORM_VALID_AFTER_FORM_HANDLERS)

                messages.info(
                    request,
                    _('Form {0} was submitted '
                      'successfully.').format(instance.form_entry.name))

                if self.can_redirect:
                    return redirect(
                        "{0}?{1}={2}".format(request.path, \
                                             self.form_sent_get_param, \
                                             instance.form_entry.slug)
                        )
                else:
                    return self._show_thanks_page(request, instance, **kwargs)

            else:
                # Fire post form validation callbacks
                fire_form_callbacks(form_entry=instance.form_entry,
                                    request=request,
                                    form=form,
                                    stage=CALLBACK_FORM_INVALID)

        else:
            # Providing initial form data by feeding entire GET dictionary
            # to the form, if ``GET_PARAM_INITIAL_DATA`` is present in the
            # GET.
            kwargs = {}
            if GET_PARAM_INITIAL_DATA in request.GET:
                kwargs = {'initial': request.GET}
            form = FormClass(**kwargs)

        theme = get_theme(request=request, as_instance=True)
        theme.collect_plugin_media(form_element_entries)

        context = {
            'form': form,
            'form_entry': instance.form_entry,
            'fobi_theme': theme,
            'fobi_form_title': instance.form_title,
            'fobi_hide_form_title': instance.hide_form_title,
            'fobi_form_submit_button_text': instance.form_submit_button_text
        }

        if not template_name:
            template_name = theme.view_embed_form_entry_ajax_template

        self.rendered_output = render_to_string(
            template_name, context, context_instance=RequestContext(request))
Exemple #28
0
def view_form_entry(request, form_entry_slug, theme=None, template_name=None):
    """
    View create form.

    :param django.http.HttpRequest request:
    :param string form_entry_slug:
    :param string template_name:
    :return django.http.HttpResponse:
    """
    try:
        kwargs = {'slug': form_entry_slug}
        if not request.user.is_authenticated():
            kwargs.update({'is_public': True})
        form_entry = FormEntry._default_manager.select_related('user') \
                              .get(**kwargs)
    except ObjectDoesNotExist as err:
        raise Http404(ugettext("Form entry not found."))

    form_element_entries = form_entry.formelemententry_set.all()[:]

    # This is where the most of the magic happens. Our form is being built
    # dynamically.
    FormClass = assemble_form_class(
        form_entry,
        form_element_entries = form_element_entries,
        request = request
        )

    if 'POST' == request.method:
        form = FormClass(request.POST, request.FILES)

        # Fire pre form validation callbacks
        fire_form_callbacks(form_entry=form_entry, request=request, form=form,
                            stage=CALLBACK_BEFORE_FORM_VALIDATION)

        if form.is_valid():
            # Fire form valid callbacks, before handling submitted plugin
            # form data.
            form = fire_form_callbacks(
                form_entry = form_entry,
                request = request,
                form = form,
                stage = CALLBACK_FORM_VALID_BEFORE_SUBMIT_PLUGIN_FORM_DATA
                )

            # Fire plugin processors
            form = submit_plugin_form_data(form_entry=form_entry,
                                           request=request, form=form)

            # Fire form valid callbacks
            form = fire_form_callbacks(form_entry=form_entry,
                                       request=request, form=form,
                                       stage=CALLBACK_FORM_VALID)

            # Run all handlers
            handler_responses, handler_errors = run_form_handlers(
                form_entry = form_entry,
                request = request,
                form = form,
                form_element_entries = form_element_entries
                )

            # Warning that not everything went ok.
            if handler_errors:
                for handler_error in handler_errors:
                    messages.warning(
                        request,
                        _("Error occured: {0}."
                          "").format(handler_error)
                        )

            # Fire post handler callbacks
            fire_form_callbacks(
                form_entry = form_entry,
                request = request,
                form = form,
                stage = CALLBACK_FORM_VALID_AFTER_FORM_HANDLERS
                )

            messages.info(
                request,
                _("Form {0} was submitted successfully."
                  "").format(form_entry.name)
                )
            return redirect(
                reverse('fobi.form_entry_submitted', args=[form_entry.slug])
                )
        else:
            # Fire post form validation callbacks
            fire_form_callbacks(form_entry=form_entry, request=request,
                                form=form, stage=CALLBACK_FORM_INVALID)

    else:
        # Providing initial form data by feeding entire GET dictionary
        # to the form, if ``GET_PARAM_INITIAL_DATA`` is present in the
        # GET.
        kwargs = {}
        if GET_PARAM_INITIAL_DATA in request.GET:
            kwargs = {'initial': request.GET}
        form = FormClass(**kwargs)

    # In debug mode, try to identify possible problems.
    if DEBUG:
        try:
            form.as_p()
        except Exception as err:
            logger.error(err)

    theme = get_theme(request=request, as_instance=True)
    theme.collect_plugin_media(form_element_entries)

    context = {
        'form': form,
        'form_entry': form_entry,
        'fobi_theme': theme,
    }

    if not template_name:
        template_name = theme.view_form_entry_template

    return render_to_response(template_name, context,
                              context_instance=RequestContext(request))
Exemple #29
0
def edit_form_handler_entry(request, form_handler_entry_id, theme=None,
                            template_name=None):
    """
    Edit form handler entry.

    :param django.http.HttpRequest request:
    :param int form_element_entry_id:
    :param string template_name:
    :return django.http.HttpResponse:
    """
    try:
        obj = FormHandlerEntry._default_manager \
                              .select_related('form_entry') \
                              .get(pk=form_handler_entry_id)
    except ObjectDoesNotExist as err:
        raise Http404(ugettext("Form handler entry not found."))

    form_entry = obj.form_entry

    form_handler_plugin = obj.get_plugin(request=request)
    form_handler_plugin.request = request

    FormHandlerPluginForm = form_handler_plugin.get_form()
    form = None

    if not FormHandlerPluginForm:
        messages.info(
            request,
            _('The form handler plugin "{0}" is not '
              'configurable!').format(form_handler_plugin.name)
            )
        return redirect('fobi.edit_form_entry', form_entry_id=form_entry.pk)

    elif 'POST' == request.method:
        form = form_handler_plugin.get_initialised_edit_form_or_404(
            data = request.POST,
            files = request.FILES
            )

        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 the object.
            obj.save()

            messages.info(
                request,
                _('The form handler plugin "{0}" was edited '
                  'successfully.').format(form_handler_plugin.name)
                )

            return redirect('fobi.edit_form_entry', form_entry_id=form_entry.pk)

    else:
        form = form_handler_plugin.get_initialised_edit_form_or_404()

    context = {
        'form': form,
        'form_entry': form_entry,
        'form_handler_plugin': form_handler_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.edit_form_handler_entry_template

    return render_to_response(template_name, context,
                              context_instance=RequestContext(request))
Exemple #30
0
def add_form_handler_entry(request, form_entry_id, form_handler_plugin_uid,
                           theme=None, template_name=None):
    """
    Add form handler entry.

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

    user_form_handler_plugin_uids = get_user_form_handler_plugin_uids(
        request.user
        )

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

    FormHandlerPlugin = form_handler_plugin_registry.get(
        form_handler_plugin_uid
        )

    # Check if we deal with form handler plugin that is only allowed to be
    # used once. In that case, check if it has been used already in the current
    # form entry.
    if not FormHandlerPlugin.allow_multiple:
        times_used = FormHandlerEntry._default_manager \
                                     .filter(form_entry__id=form_entry_id,
                                             plugin_uid=FormHandlerPlugin.uid) \
                                     .count()
        if times_used > 0:
            raise Http404(ugettext("The {0} plugin can be used only once in a "
                                   "form.").format(FormHandlerPlugin.name))

    form_handler_plugin = FormHandlerPlugin(user=request.user)
    form_handler_plugin.request = request

    FormHandlerPluginForm = form_handler_plugin.get_form()
    form = None

    obj = FormHandlerEntry()
    obj.form_entry = form_entry
    obj.plugin_uid = form_handler_plugin_uid
    obj.user = request.user

    save_object = False

    if not FormHandlerPluginForm:
        save_object = True

    elif 'POST' == request.method:
        form = form_handler_plugin.get_initialised_create_form_or_404(
            data = request.POST,
            files = request.FILES
            )
        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

    else:
        form = form_handler_plugin.get_initialised_create_form_or_404()

    if save_object:
        # Save the object.
        obj.save()

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

    context = {
        'form': form,
        'form_entry': form_entry,
        'form_handler_plugin': form_handler_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_handler_entry_template

    return render_to_response(template_name, context,
                              context_instance=RequestContext(request))
Exemple #31
0
 def __init__(self, *args, **kwargs):
     super(FormFieldsetEntryForm, self).__init__(*args, **kwargs)
     theme = get_theme(request=None, as_instance=True)
     self.fields['name'].widget = forms.widgets.TextInput(
         attrs={'class': theme.form_element_html_class}
         )
Exemple #32
0
from .settings import (
    FIT_METHODS_CHOICES,
    DEFAULT_FIT_METHOD,
    DEFAULT_SIZE,
    SIZES,
    IMAGES_UPLOAD_DIR,
)

__title__ = 'fobi.contrib.plugins.form_elements.content.content_image.forms'
__author__ = 'Artur Barseghyan <*****@*****.**>'
__copyright__ = '2014-2019 Artur Barseghyan'
__license__ = 'GPL 2.0/LGPL 2.1'
__all__ = ('ContentImageForm', )

theme = get_theme(request=None, as_instance=True)


class ContentImageForm(forms.Form, BasePluginForm):
    """Form for ``ContentImagePlugin``."""

    plugin_data_fields = [
        ("file", ""),
        ("alt", ""),
        ("fit_method", DEFAULT_FIT_METHOD),
        ("size", DEFAULT_SIZE),
    ]

    file = forms.ImageField(label=_("Image"),
                            required=True,
                            widget=forms.widgets.ClearableFileInput()
Exemple #33
0
def edit_form_entry(request, form_entry_id, theme=None, template_name=None):
    """
    Edit form entry.

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

    if 'POST' == request.method:
        # The form entry form (does not contain form elenments)
        form = FormEntryForm(request.POST, request.FILES, instance=form_entry,
                             request=request)

        if 'ordering' in request.POST:
            form_element_entry_formset = FormElementEntryFormSet(
                request.POST,
                request.FILES,
                queryset = form_entry.formelemententry_set.all(),
                #prefix = 'form_element'
                )
            # If form elements aren't properly made (developers's fault)
            # there might be problems with saving the ordering - likely
            # in case of hidden elements only. Thus, we want to avoid
            # errors here.
            try:
                if form_element_entry_formset.is_valid():
                    form_element_entry_formset.save()
                    messages.info(
                        request,
                        _("Elements ordering edited successfully.")
                        )
                    return redirect(
                        reverse('fobi.edit_form_entry',
                                kwargs={'form_entry_id': form_entry_id})
                        )
            except MultiValueDictKeyError as err:
                messages.error(
                    request,
                    _("Errors occured while trying to change the "
                      "elements ordering!")
                    )
                return redirect(
                    reverse('fobi.edit_form_entry',
                            kwargs={'form_entry_id': form_entry_id})
                    )
        else:
            form_element_entry_formset = FormElementEntryFormSet(
                queryset = form_entry.formelemententry_set.all(),
                #prefix = 'form_element'
                )

        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            try:
                obj.save()
                messages.info(
                    request,
                    _('Form {0} was edited successfully.').format(
                        form_entry.name
                        )
                    )
                return redirect(
                    reverse('fobi.edit_form_entry',
                            kwargs={'form_entry_id': form_entry_id})
                    )
            except IntegrityError as err:
                messages.info(
                    request,
                    _('Errors occured while saving the form: {0}.').format(
                        str(err)
                        )
                    )
    else:
        # The form entry form (does not contain form elenments)
        form = FormEntryForm(instance=form_entry, request=request)

        form_element_entry_formset = FormElementEntryFormSet(
            queryset = form_entry.formelemententry_set.all(),
            #prefix = 'form_element'
            )

    # In case of success, we don't need this (since redirect would happen).
    # Thus, fetch only if needed.
    form_elements = form_entry.formelemententry_set.all()
    form_handlers = form_entry.formhandlerentry_set.all()[:]
    used_form_handler_uids = [form_handler.plugin_uid for form_handler \
                                                      in form_handlers]
    all_form_entries = FormEntry._default_manager.only('id', 'name', 'slug') \
                                .filter(user__pk=request.user.pk)

    # List of form element plugins allowed to user
    user_form_element_plugins = get_user_form_element_plugins_grouped(
        request.user
        )
    # List of form handler plugins allowed to user
    user_form_handler_plugins = get_user_form_handler_plugins(
        request.user,
        exclude_used_singles = True,
        used_form_handler_plugin_uids = used_form_handler_uids
        )

    # Assembling the form for preview
    FormClass = assemble_form_class(
        form_entry,
        origin = 'edit_form_entry',
        origin_kwargs_update_func = append_edit_and_delete_links_to_field,
        request = request
        )

    assembled_form = FormClass()

    # In debug mode, try to identify possible problems.
    if DEBUG:
        try:
            assembled_form.as_p()
        except Exception as err:
            logger.error(err)

    # If no theme provided, pick a default one.
    if not theme:
        theme = get_theme(request=request, as_instance=True)

    theme.collect_plugin_media(form_elements)

    context = {
        'form': form,
        'form_entry': form_entry,
        'form_elements': form_elements,
        'form_handlers': form_handlers,
        'all_form_entries': all_form_entries,
        'user_form_element_plugins': user_form_element_plugins,
        'user_form_handler_plugins': user_form_handler_plugins,
        'assembled_form': assembled_form,
        'form_element_entry_formset': form_element_entry_formset,
        'fobi_theme': theme,
    }

    if not template_name:
        template_name = theme.edit_form_entry_template

    return render_to_response(
        template_name, context, context_instance=RequestContext(request)
        )
Exemple #34
0
 def __init__(self, *args, **kwargs):
     super(FormFieldsetEntry, self).__init__(*args, **kwargs)
     theme = get_theme(request=None, as_instance=True)
     self.fields['name'].widget = forms.widgets.TextInput(
         attrs={'class': theme.form_element_html_class})
from django.forms.fields import MultipleChoiceField
from django.forms.widgets import CheckboxSelectMultiple
from django.utils.translation import ugettext_lazy as _

from fobi.base import FormFieldPlugin, form_element_plugin_registry, get_theme
from fobi.constants import (
    SUBMIT_VALUE_AS_VAL, SUBMIT_VALUE_AS_REPR
    )
from fobi.helpers import get_select_field_choices, safe_text

from . import UID
from .forms import CheckboxSelectMultipleInputForm
from .settings import SUBMIT_VALUE_AS

theme = get_theme(request=None, as_instance=True)

class CheckboxSelectMultipleInputPlugin(FormFieldPlugin):
    """
    Checkbox select multiple field plugin.
    """
    uid = UID
    name = _("Checkbox select multiple")
    group = _("Fields")
    form = CheckboxSelectMultipleInputForm

    def get_form_field_instances(self):
        """
        Get form field instances.
        """
        choices = get_select_field_choices(self.data.choices)
Exemple #36
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))