Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using wagtail-django-recaptcha my form disappear from the list of pages. #28

Open
jamilatta opened this issue Jan 10, 2019 · 2 comments

Comments

@jamilatta
Copy link

Hi

I using Wagtail Django Recaptcha in my project but after it the label to add page disappear.

I already searched on google but did not enter anything

Look my code:

from __future__ import absolute_import, unicode_literals

from datetime import date

from django import forms
from django.db import models
from django.utils.text import slugify
from django.forms import widgets
from django.utils.translation import ugettext_lazy as _

from wagtail.search import index
from wagtail.core.models import Page
from wagtail.admin.utils import send_mail
from wagtail.core.fields import StreamField, RichTextField
from modelcluster.fields import ParentalKey
from wagtail.admin.edit_handlers import StreamFieldPanel

from wagtail.admin.edit_handlers import (
    FieldPanel, FieldRowPanel,
    InlinePanel, MultiFieldPanel
)

from wagtail.images.blocks import ImageChooserBlock
from wagtail.core.blocks import (StructBlock,
                                 StreamBlock,
                                 FieldBlock,
                                 CharBlock,
                                 RichTextBlock)
from wagtail.contrib.forms.models import (AbstractFormField,
                                          FORM_FIELD_CHOICES)
from wagtail.contrib.forms.edit_handlers import FormSubmissionsPanel

from mosaic.models import MosaicIndexPage
from highlight.models import Highlight
from wagtailcaptcha.models import WagtailCaptchaEmailForm, WagtailCaptchaForm
from .forms import CustomFormBuilderEmail, CustomFormBuilder


class ImageFormatChoiceBlock(FieldBlock):
    field = forms.ChoiceField(choices=(
        ('left', 'Wrap left'),
        ('right', 'Wrap right'),
        ('mid', 'Mid width'),
        ('full', 'Full width'),
    ))


class ImageBlock(StructBlock):
    image = ImageChooserBlock()
    caption = RichTextBlock()
    alignment = ImageFormatChoiceBlock()


class HomePageBodyBlock(StreamBlock):
    heading = CharBlock(icon="title", classname="title")
    paragraph = RichTextBlock(icon="pilcrow")
    image = ImageBlock(label="Aligned image", icon="image")


class HomePage(Page):
    body = StreamField(HomePageBodyBlock())

    search_fields = Page.search_fields + [
        index.SearchField('body'),
    ]

    content_panels = Page.content_panels + [
        StreamFieldPanel('body'),
    ]

    def get_context(self, request):
        context = super(HomePage, self).get_context(request)
        mosaic = MosaicIndexPage.objects.live().first()
        highlights = Highlight.objects.live().all()
        context['mosaic'] = mosaic
        context['highlights'] = highlights
        return context


class FormEmailField(AbstractFormField):
    CHOICES = FORM_FIELD_CHOICES + (('time', 'Time'),)

    page = ParentalKey('FormEmailPage', on_delete=models.CASCADE,
                       related_name='form_fields')
    textBefore = models.TextField(verbose_name=_('Text before'), max_length=512, blank=True,
                                  help_text=_('Write a text to be display before the field.'))
    textAfter = models.TextField(verbose_name=_('Text after'), max_length=512, blank=True,
                                 help_text=_('Write a text to be display after the field.'))
    group = models.CharField(verbose_name=_('Group'), max_length=512, blank=True,
                             help_text=_('Set the group of this field'))

    field_type = models.CharField(
        verbose_name='field type',
        max_length=16,
        # use the choices tuple defined above
        choices=CHOICES
    )

    panels = AbstractFormField.panels + [
        FieldPanel('textBefore'),
        FieldPanel('textAfter'),
        FieldPanel('group'),
    ]


class FormEmailPage(WagtailCaptchaEmailForm):
    is_creatable = False
    intro = models.CharField(max_length=255, null=True, blank=True)
    thank_you_text = RichTextField(blank=True)

    form_builder = CustomFormBuilderEmail

    content_panels = WagtailCaptchaEmailForm.content_panels + [
        FormSubmissionsPanel(),
        FieldPanel('intro', classname="full"),
        InlinePanel('form_fields', label=_("Campos")),
        FieldPanel('thank_you_text', classname="full"),
        MultiFieldPanel([
            FieldRowPanel([
                FieldPanel('from_address', classname="col6"),
                FieldPanel('to_address', classname="col6"),
            ]),
            FieldPanel('subject'),
        ], "Email"),
    ]

    class Meta:
        verbose_name = _("Formulário com e-mail")
        verbose_name_plural = _("Formulários com e-mail")

    def get_form(self, *args, **kwargs):
        form = super().get_form(*args, **kwargs)

        # iterate through the fields in the generated form
        for name, field in form.fields.items():

            group_name = ''
            # Get the group of the field based on name
            for form_field in kwargs['page'].get_form_fields():
                if form_field.label == field.label:
                    if form_field.group:
                        group_name = form_field.group
                        field.widget.attrs.update({'group': form_field.group})

            # for all fields, get any existing CSS classes and add 'form-control'
            # ensure the 'class' attribute is a string of classes with spaces
            css_classes = field.widget.attrs.get('class', '').split()
            css_classes.append('form-control')
            css_classes.append(slugify(group_name))
            field.widget.attrs.update({'class': ' '.join(css_classes)})
        return form

    def send_mail(self, form):
        addresses = [x.strip() for x in self.to_address.split(',')]
        content = []

        # {'Grupo1':
        #   [{'campo1': 'valor1'}, {'campo2': 'valor2'}],
        #  'Grupo2':
        #   [{'campo1': 'valor1'}]}
        group_dict = {}

        for field in form:
            value = field.value()

            group = field.field.widget.attrs.get('group', '')

            if isinstance(value, list):
                value = ', '.join(value)

            if group:
                group_dict.setdefault(group, [])
                group_dict[group].append({field.label: value})
            else:
                content.append('{}: {}</br></br>'.format(field.label, value))

        for k, items in sorted(group_dict.items()):
            content.append('<hr>Grupo:{}<ul>'.format(k))
            for item in items:
                for k, v in item.items():
                    content.append('<li>{}: {}</li>'.format(k, v))
            content.append('</ul>')

        submitted_date_str = date.today().strftime('%x')
        content.append('{}: {}'.format(
            'Data do envio', submitted_date_str))
        content.append('{}: <a href="{}">{}<a>'.format(
            'Enviado via', self.full_url, self.title))
        content = '</br></br>'.join(content)
        subject = self.subject + " - " + submitted_date_str
        send_mail(subject, content, addresses, self.from_address, html_message=content)


class FormField(AbstractFormField):
    CHOICES = FORM_FIELD_CHOICES + (('time', 'Time'),)

    page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
    textBefore = models.TextField(verbose_name=_('Text before'), max_length=512, blank=True,
                                  help_text=_('Write a text to be display before the field.'))
    textAfter = models.TextField(verbose_name=_('Text after'), max_length=512, blank=True,
                                 help_text=_('Write a text to be display after the field.'))

    field_type = models.CharField(
        verbose_name='field type',
        max_length=16,
        # use the choices tuple defined above
        choices=CHOICES
    )

    panels = AbstractFormField.panels + [
        FieldPanel('textBefore'),
        FieldPanel('textAfter'),
    ]


class FormPage(WagtailCaptchaForm):
    intro = models.CharField(max_length=255, null=True, blank=True)
    thank_you_text = RichTextField(blank=True)

    form_builder = CustomFormBuilder

    content_panels = WagtailCaptchaForm.content_panels + [
        FormSubmissionsPanel(),
        FieldPanel('intro', classname="full"),
        InlinePanel('form_fields', label=_("Campos")),
        FieldPanel('thank_you_text', classname="full"),
    ]

    class Meta:
        verbose_name = _("Formulário sem e-mail")
        verbose_name_plural = _("Formulários sem e-mail")

Look my dependencies:

Django==1.11.13
wagtail==2.0.2
wagtail-django-recaptcha==1.0
@jamilatta
Copy link
Author

When I run makemigrations:

Its generate a unknown migration, like this:

class Migration(migrations.Migration):

    dependencies = [
        ('home', '0016_auto_20181101_1623'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='formemailpage',
            name='form_name',
        ),
        migrations.RemoveField(
            model_name='formemailpage',
            name='form_short_name',
        ),
        migrations.RemoveField(
            model_name='formpage',
            name='form_name',
        ),
        migrations.RemoveField(
            model_name='formpage',
            name='form_short_name',
        ),
    ]

@jamilatta
Copy link
Author

I can`t see "Formulário com e-mail" in this list:

screenshot 2019-01-10 17 24 59

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant