Example #1
0
def test_simple_form(monkeypatch, rf, admin_user, greeting_form, push_messages,
                     valid_data, method, anon, override_form):
    fd = greeting_form
    message = f'zzz-å{get_random_string(12)}Ö'
    data = {
        'greeting': message,
        'upload': ContentFile(VERY_SMALL_JPEG, name='hello.jpg'),
        fd.submit_flag_name: 'true',
    }
    if not valid_data:
        data.pop('greeting')

    if method == 'POST':
        request = rf.post('/', data)
    elif method == 'GET':
        data.pop('upload')  # can't upload via GET
        request = rf.get('/', data)

    request.user = (AnonymousUser() if anon else admin_user)
    request._messages = BaseStorage(request)
    kwargs = dict(
        push_messages=push_messages,
        disable_redirection=True,
    )
    if override_form == 'kwarg':
        kwargs['form_class'] = OverriddenDesignedForm
    elif override_form == 'settings':
        # Can't use the pytest-django settings fixture, since `form_designer.settings`
        # has non-lazy copies of Django settings taken at that module's import time.
        monkeypatch.setattr(
            fd_settings, 'DESIGNED_FORM_CLASS',
            'form_designer.tests.test_basics.OverriddenDesignedForm')

    context = process_form(request, fd, **kwargs)
    assert context['form_success'] == valid_data

    # Test that a message was (or was not) pushed
    assert len(request._messages._queued_messages) == int(push_messages)

    if valid_data:
        if override_form:  # If we've overridden the form, we expect an uppercase message
            message = message.upper()

        # Test that the form log was saved:
        flog = FormLog.objects.get(form_definition=fd)
        assert flog == context[
            'form_log']  # (and it's the same object in the context)
        name_to_value = {d['name']: d['value'] for d in flog.data}
        assert name_to_value['greeting'] == message
        if name_to_value.get('upload'):
            assert isinstance(name_to_value['upload'], File)
        if not anon:
            assert flog.created_by == admin_user

        # Test that the email was sent:
        sent_email = mail.outbox[-1]

        assert message in sent_email.subject  # (since we customized the subject with a template)
        assert 'greetingbot' in sent_email.message().get(
            "Reply-To")  # (since we customized the reply-to address)
def tinymce_formdesigner(context, html):
    """
    This tag expects a chunk of HTML and will look for any <img> tags that
    have a class of tinymce_formdesigner_placeholder, which will be inserted
    by the tinymce plugin. It then replaces those images with the actual form
    output
    """
    soup = BeautifulSoup(html)
    for tag in soup.findAll("img", { "class": "tinymce_formdesigner_placeholder" }):
        try:
            form_definition = FormDefinition.objects.get(name=tag['id'])
        except FormDefinition.DoesNotExist:
            continue

        if 'request' not in context:
            tag.append(BeautifulSoup('<!-- Failed to render your form. You need to include the request object in the context -->'))
            continue

        result = process_form(context['request'], form_definition,
                              extra_context=RequestContext(context['request']),
                              disable_redirection=True)

        form_template = form_definition.form_template_name or app_settings.DEFAULT_FORM_TEMPLATE

        form_html = BeautifulSoup(render_to_string(form_template, result))

        tag.replaceWith(form_html)

    return str(soup)
    def render(self, context, instance, placeholder):
        if instance.form_definition.form_template_name:
            self.render_template = instance.form_definition.form_template_name
        else:
            self.render_template = settings.DEFAULT_FORM_TEMPLATE

        # Redirection does not work with CMS plugin, hence disable:
        return process_form(context['request'], instance.form_definition, context, disable_redirection=True)
    def render(self, context, instance, placeholder):
        if instance.form_definition.form_template_name:
            self.render_template = instance.form_definition.form_template_name
        else:
            self.render_template = settings.DEFAULT_FORM_TEMPLATE

        # Redirection does not work with CMS plugin, hence disable:
        return process_form(context['request'], instance.form_definition, context, disable_redirection=True)
 def render(self, context, instance, placeholder):
     if instance.form_definition.form_template_name:
         self.render_template = instance.form_definition.form_template_name
     else:
         self.render_template = settings.DEFAULT_FORM_TEMPLATE
     return process_form(context['request'],
                         instance.form_definition,
                         context,
                         is_cms_plugin=True)
    def render(self, request, instance, **kwargs):
        # While overwriting get_context() would be sufficient here, this is rather easier to understand.
        # Implemented a custom rendering function instead.

        # The process_form() function is designed with Django CMS in mind,
        # and responds to both the GET and POST request.
        context = process_form(request, instance.form_definition, {}, **{_disable_redirection: True})
        context['messages'] = get_messages(request)  # No matter what, because the template needs it.

        # Render the plugin
        render_template = self.get_render_template(request, instance, **kwargs)
        return self.render_to_string(request, render_template, context)
    def render(self, context, instance, placeholder):
        request = context['request']
               
        if instance.form_definition.form_template_name:
            self.render_template = instance.form_definition.form_template_name
        else:
            self.render_template = settings.DEFAULT_FORM_TEMPLATE

        # Redirection does not work with CMS plugin, hence disable:
        result = process_form(request, instance.form_definition, context)
        if isinstance(result, HttpResponseRedirect):
            raise ForceResponse(result)
        else:
            return result
Example #8
0
    def render(self, context, instance, placeholder):

        context.update({
            'form_template_name':
            instance.form_definition.form_template_name
            or settings.DEFAULT_FORM_TEMPLATE,
        })

        disable_redirection = 'form_designer.middleware.RedirectMiddleware' not in django_settings.MIDDLEWARE_CLASSES

        response = process_form(context['request'],
                                instance.form_definition,
                                context,
                                disable_redirection=disable_redirection)

        if isinstance(response, HttpResponseRedirect):
            raise HttpRedirectException(response, "Redirect")
        return response
    def get_context(self, request, instance, **kwargs):
        """
        Return the context to use in the template defined by ``render_template`` (or :func:`get_render_template`).
        By default, it returns the model instance as ``instance`` field in the template.
        RUS: Возвращает контекст для шаблонов плагина "дизайнер форм".
        """

        sekizai_varname = sekizai_get_varname()

        context = {
            'instance': instance,
            'config': config,
            sekizai_varname: getattr(request, sekizai_varname),
        }

        return process_form(request,
                            instance.form_definition,
                            context,
                            disable_redirection=True)
    def render(self, context, instance, placeholder):
        
        context.update({
            'form_template_name':instance.form_definition.form_template_name or settings.DEFAULT_FORM_TEMPLATE,
            })

        disable_redirection = 'form_designer.middleware.RedirectMiddleware' not in django_settings.MIDDLEWARE_CLASSES

        response = process_form(
            context['request'], 
            instance.form_definition, 
            context, 
            disable_redirection=disable_redirection
            )

        if isinstance(response, HttpResponseRedirect):
            raise HttpRedirectException(
                response, 
                "Redirect"
                )
        return response
    def render(self, context, instance, placeholder):
        
        context.update({
            'form_template_name':instance.form_definition.form_template_name or settings.DEFAULT_FORM_TEMPLATE,
            })

        disable_redirection = 'form_designer.middleware.RedirectMiddleware' not in django_settings.MIDDLEWARE_CLASSES

        response = process_form(
            context['request'], 
            instance.form_definition, 
            context, 
            disable_redirection=disable_redirection
            )

        if isinstance(response, HttpResponseRedirect):
            # If process_form returns a redirect, stick it in the request object
            # for the response middleware to catch and act on.
            # Return the context object, because although it's not displayed,
            # the plugin render system will break if it doesn't get it.
            context['request'].formDesingerRedirect = response
            return context

        return response
Example #12
0
    def render(self, context, instance, placeholder):

        context.update({
            'form_template_name':
            instance.form_definition.form_template_name
            or settings.DEFAULT_FORM_TEMPLATE,
        })

        disable_redirection = 'form_designer.middleware.RedirectMiddleware' not in django_settings.MIDDLEWARE_CLASSES

        response = process_form(context['request'],
                                instance.form_definition,
                                context,
                                disable_redirection=disable_redirection)

        if isinstance(response, HttpResponseRedirect):
            # If process_form returns a redirect, stick it in the request object
            # for the response middleware to catch and act on.
            # Return the context object, because although it's not displayed,
            # the plugin render system will break if it doesn't get it.
            context['request'].formDesingerRedirect = response
            return context

        return response
 def get_context(self, request, instance, **kwargs):
     context = {}
     # The process_form() function is designed with Django CMS in mind,
     # and responds to both the GET and POST request.
     return process_form(request, instance.form_definition, context, is_cms_plugin=True)
def test_simple_form(
    monkeypatch, rf, admin_user,
    greeting_form, push_messages, valid_data, method, anon, override_form
):
    fd = greeting_form
    message = 'zzz-å%sÖ' % get_random_string()
    data = {
        'greeting': message,
        'upload': ContentFile(VERY_SMALL_JPEG, name='hello.jpg'),
        fd.submit_flag_name: 'true',
    }
    if not valid_data:
        data.pop('greeting')

    if method == 'POST':
        request = rf.post('/', data)
    elif method == 'GET':
        data.pop('upload')  # can't upload via GET
        request = rf.get('/', data)

    request.user = (AnonymousUser() if anon else admin_user)
    request._messages = BaseStorage(request)
    kwargs = dict(
        push_messages=push_messages,
        disable_redirection=True,
    )
    if override_form == 'kwarg':
        kwargs['form_class'] = OverriddenDesignedForm
    elif override_form == 'settings':
        # Can't use the pytest-django settings fixture, since `form_designer.settings`
        # has non-lazy copies of Django settings taken at that module's import time.
        monkeypatch.setattr(
            fd_settings,
            'DESIGNED_FORM_CLASS',
            'form_designer.tests.test_basics.OverriddenDesignedForm'
        )

    context = process_form(request, fd, **kwargs)
    assert context['form_success'] == valid_data

    # Test that a message was (or was not) pushed
    assert len(request._messages._queued_messages) == int(push_messages)

    if valid_data:
        if override_form:  # If we've overridden the form, we expect an uppercase message
            message = message.upper()

        # Test that the form log was saved:
        flog = FormLog.objects.get(form_definition=fd)
        assert flog == context['form_log']  # (and it's the same object in the context)
        name_to_value = {d['name']: d['value'] for d in flog.data}
        assert name_to_value['greeting'] == message
        if name_to_value.get('upload'):
            assert isinstance(name_to_value['upload'], File)
        if not anon:
            assert flog.created_by == admin_user

        # Test that the email was sent:
        sent_email = mail.outbox[-1]

        assert message in sent_email.subject  # (since we customized the subject with a template)
        assert 'greetingbot' in sent_email.message().get("Reply-To")  # (since we customized the reply-to address)
 def render(self, context, instance, placeholder):
     if instance.form_definition.form_template_name:
         self.render_template = instance.form_definition.form_template_name
     else:
         self.render_template = settings.DEFAULT_FORM_TEMPLATE
     return process_form(context['request'], instance.form_definition, context, is_cms_plugin=True)