Ejemplo n.º 1
0
def test_data_handler(survey_form_entry, location, study, form_element_float,
                      form_element_help_text, form_element_time_start, mocker):
    """Tests the custom Fobi data handler by instantiating a sample
    survey, surveyrow, and surveycomponent with saved data"""

    float_data = json.loads(form_element_float.plugin_data)
    submitted_float_data = 5

    time_start_data = json.loads(form_element_time_start.plugin_data)
    submitted_time_start_data = datetime.time(5, 45, 00)

    request = mocker.MagicMock(spec=requests.Response)
    form_class = assemble_form_class(form_entry=survey_form_entry)

    form_class = assemble_form_class(form_entry=survey_form_entry)
    form = form_class(data={float_data['name']: submitted_float_data,
                            time_start_data['name']: submitted_time_start_data})

    assert form.is_valid()

    plugin = CollectDataPlugin()
    plugin.run(form=form,
               form_entry=survey_form_entry,
               request=request)

    survey = Survey.objects.first()
    rows = SurveyRow.objects.filter(survey=survey)

    row = rows[0]
    components = SurveyComponent.objects.filter(row=row)
    component = components[0]

    assert len(rows) == 1
    assert len(components) == 1

    assert survey.id
    assert survey.time_start
    assert survey.location == location
    assert survey.study == study

    assert row.id
    assert not row.total
    assert row.survey == survey

    assert component.id
    assert component.detail_level == 'basic'
    assert component.name == float_data['name']
    assert component.label == float_data['label']
    assert component.type == form_element_float.plugin_uid
    assert component.position == form_element_float.position
    assert float(component.saved_data) == submitted_float_data
    assert component.row == row
Ejemplo n.º 2
0
def get_assembled_form(form_entry):
    """
    Gets assembled form.

    :param fobi.models.FormEntry form_entry:
    :return django.forms.Form:
    """
    # TODO
    FormClass = assemble_form_class(form_entry)
    form = FormClass()
    return form
Ejemplo n.º 3
0
def get_assembled_form(form_entry, request=None):
    """
    Gets assembled form.

    :param fobi.models.FormEntry form_entry:
    :param django.http.HttpRequest request:
    :return django.forms.Form:
    """
    # TODO
    FormClass = assemble_form_class(form_entry, request=request)
    form = FormClass()
    return form
Ejemplo n.º 4
0
def get_assembled_form(form_entry, request=None):
    """
    Gets assembled form.

    :param fobi.models.FormEntry form_entry:
    :param django.http.HttpRequest request:
    :return django.forms.Form:
    """
    # TODO
    FormClass = assemble_form_class(form_entry, request=request)
    form = FormClass()
    return form
Ejemplo n.º 5
0
def form(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 request.method == 'POST':
        print("guardo")
    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)


    context = {
        'form': form,
    }


    return render_to_response('form.html', context,
                              context_instance=RequestContext(request))
Ejemplo n.º 6
0
def form(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 request.method == 'POST':
        print("guardo")
    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)

    context = {
        'form': form,
    }

    return render_to_response('form.html',
                              context,
                              context_instance=RequestContext(request))
Ejemplo n.º 7
0
    def test_01_assemble_form_class_and_render_form(self):
        """Test form class assembling and rendering."""
        flow = []

        # Getting entry with created plugins
        form_entry = create_form_with_entries()
        flow.append(form_entry)

        FormClass = assemble_form_class(form_entry)
        flow.append(FormClass)

        form = FormClass()
        flow.append(form)

        rendered_form = form.as_p()
        flow.append(rendered_form)

        return flow
Ejemplo n.º 8
0
    def test_01_assemble_form_class_and_render_form(self):
        """
        Test form class assembling and rendering.
        """
        flow = []

        # Getting entry with created plugins
        form_entry = create_form_with_entries()
        flow.append(form_entry)

        FormClass = assemble_form_class(form_entry)
        flow.append(FormClass)

        form = FormClass()
        flow.append(form)

        rendered_form = form.as_p()
        flow.append(rendered_form)

        return flow
Ejemplo n.º 9
0
    def test_01_assemble_form_class_and_render_form(self):
        """Test form class assembling and rendering."""
        flow = []

        # Getting entry with created plugins
        # form_entry = create_form_with_entries(
        #     data=TEST_DYNAMIC_FORMS_DEFINITION_DATA
        # )
        flow.append(self.form_entry)

        form_class = assemble_form_class(self.form_entry)
        flow.append(form_class)

        form = form_class()
        flow.append(form)

        rendered_form = form.as_p()
        flow.append(rendered_form)

        return flow
    def test_01_assemble_form_class_and_render_form(self):
        """Test form class assembling and rendering."""
        flow = []

        # Getting entry with created plugins
        # form_entry = create_form_with_entries(
        #     data=TEST_DYNAMIC_FORMS_DEFINITION_DATA
        # )
        flow.append(self.form_entry)

        form_class = assemble_form_class(self.form_entry)
        flow.append(form_class)

        form = form_class()
        flow.append(form)

        rendered_form = form.as_p()
        flow.append(rendered_form)

        return flow
Ejemplo n.º 11
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))
Ejemplo n.º 12
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))
Ejemplo n.º 13
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)
            )
Ejemplo n.º 14
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))
Ejemplo n.º 15
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))
Ejemplo n.º 16
0
def inscripcion_extra(request):
    m = request.GET.get('m')
    text = request.GET.get('text')
    try:
        idInscripto = decode_data(m, text)
    except:
        messages.error(request, u'La url no es correcta.')
        return HttpResponseRedirect(reverse('inicio'))

    inscripto = get_object_or_404(InscripcionBase, pk=idInscripto)

    if inscripto.datos is not None:
        messages.error(request, u'Ya ha completado los datos extras.')
        return HttpResponseRedirect(reverse('inicio'))

    form_entry = inscripto.actividad.formDinamico

    form_element_entries = form_entry.formelemententry_set.all()[:]
    print(form_element_entries)
    # 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)

        if form.is_valid():
            field_name_to_label_map, cleaned_data = get_processed_form_data(
                form, form_element_entries)
            for key, value in cleaned_data.items():
                if isinstance(value, (datetime.datetime, datetime.date)):
                    cleaned_data[key] = value.isoformat() if hasattr(
                        value, 'isoformat') else value
            inscripto.datos = json.dumps(cleaned_data)
            inscripto.save()

            mensaje = u'Su solicitud ha sido procesada con éxito. Gracias por inscribirse'
            messages.success(request, mensaje)
            return HttpResponseRedirect(reverse('inicio'))
    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)

    context = {
        'form': form,
        'inscripto': inscripto,
    }

    return render_to_response('formextra.html',
                              context,
                              context_instance=RequestContext(request))
Ejemplo n.º 17
0
def inscripcion_extra(request):
    m = request.GET.get('m')
    text = request.GET.get('text')
    try:
        idInscripto = decode_data(m, text)
    except:
        messages.error(request, u'La url no es correcta.')
        return HttpResponseRedirect(reverse('inicio'))

    inscripto = get_object_or_404(InscripcionBase, pk=idInscripto)

    if inscripto.datos is not None:
        messages.error(request, u'Ya ha completado los datos extras.')
        return HttpResponseRedirect(reverse('inicio'))

    form_entry = inscripto.actividad.formDinamico

    form_element_entries = form_entry.formelemententry_set.all()[:]
    print(form_element_entries)
    # 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)

        if form.is_valid():
            field_name_to_label_map, cleaned_data = get_processed_form_data(
            form,
            form_element_entries
            )
            for key, value in cleaned_data.items():
                if isinstance(value, (datetime.datetime, datetime.date)):
                    cleaned_data[key] = value.isoformat() if hasattr(value, 'isoformat') else value
            inscripto.datos = json.dumps(cleaned_data)
            inscripto.save()

            mensaje = u'Su solicitud ha sido procesada con éxito. Gracias por inscribirse'
            messages.success(request, mensaje)
            return HttpResponseRedirect(reverse('inicio'))
    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)

    context = {
        'form': form,
        'inscripto': inscripto,
    }

    return render_to_response('formextra.html', context,
                              context_instance=RequestContext(request))
Ejemplo n.º 18
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)
        )