예제 #1
0
def submission_article(request, survey_id, submission_id):
    # get the specific submission entry
    survey_page = get_object_or_404(Page, id=survey_id).specific
    SubmissionClass = survey_page.get_submission_class()

    submission = SubmissionClass.objects.filter(
        page=survey_page).filter(pk=submission_id).first()
    if not submission.article_page:
        survey_index_page = (
            SurveysIndexPage.objects.descendant_of(
                request.site.root_page).live().first())
        body = []
        for value in submission.get_data().values():
            body.append({"type": "paragraph", "value": str(value)})
        article = ArticlePage(
            title='yourwords-entry-%s' % cautious_slugify(submission_id),
            slug='yourwords-entry-%s' % cautious_slugify(submission_id),
            body=json.dumps(body)
        )
        survey_index_page.add_child(instance=article)
        article.save_revision()
        article.unpublish()

        submission.article_page = article
        submission.save()
        return redirect('/admin/pages/%d/move/' % article.id)
    return redirect('/admin/pages/%d/edit/' % submission.article_page.id)
예제 #2
0
def submission_article(request, survey_id, submission_id):
    # get the specific submission entry
    survey_page = get_object_or_404(Page, id=survey_id).specific
    SubmissionClass = survey_page.get_submission_class()

    submission = SubmissionClass.objects.filter(page=survey_page).filter(
        pk=submission_id).first()
    if not submission.article_page:
        survey_index_page = (SurveysIndexPage.objects.descendant_of(
            request.site.root_page).live().first())
        body = []
        for value in submission.get_data().values():
            body.append({"type": "paragraph", "value": str(value)})
        article = ArticlePage(
            title='yourwords-entry-%s' % cautious_slugify(submission_id),
            slug='yourwords-entry-%s' % cautious_slugify(submission_id),
            body=json.dumps(body))
        survey_index_page.add_child(instance=article)
        article.save_revision()
        article.unpublish()

        submission.article_page = article
        submission.save()
        return redirect('/admin/pages/%d/move/' % article.id)
    return redirect('/admin/pages/%d/edit/' % submission.article_page.id)
예제 #3
0
def convert_to_article(request, entry_id):
    def get_entry_author(entry):
        written_by_user = '******' % entry.user.username
        written_by_anon = 'Written by: Anonymous'
        if entry.hide_real_name:
            return written_by_anon
        return written_by_user

    entry = get_object_or_404(YourWordsCompetitionEntry, pk=entry_id)
    if not entry.article_page:
        competition_index_page = (
            YourWordsCompetitionIndexPage.objects.descendant_of(
                request.site.root_page).live().first())
        article = ArticlePage(title=entry.story_name,
                              slug='yourwords-entry-%s-%s' %
                              (cautious_slugify(entry.story_name), entry.pk),
                              body=json.dumps([{
                                  "type": "paragraph",
                                  "value": get_entry_author(entry)
                              }, {
                                  "type": "paragraph",
                                  "value": entry.story_text
                              }]))
        competition_index_page.add_child(instance=article)
        article.save_revision()
        article.unpublish()

        entry.article_page = article
        entry.save()
        return redirect('/admin/pages/%d/move/' % article.id)
    return redirect('/admin/pages/%d/edit/' % entry.article_page.id)
예제 #4
0
 def tabs_with_slugs(self):
     return [
         {
             "label": label,
             "slug": cautious_slugify(label),
         }
         for label in self.tabs
     ]
예제 #5
0
    def test_escapes_non_latin_chars(self):
        test_cases = [
            ('Straßenbahn', 'straxdfenbahn'),
            ('Спорт!', 'u0421u043fu043eu0440u0442'),
            ('〔山脈〕', 'u5c71u8108'),
        ]

        for (original, expected_result) in test_cases:
            self.assertEqual(cautious_slugify(original), expected_result)
예제 #6
0
파일: test_utils.py 프로젝트: jams2/wagtail
    def test_escapes_non_latin_chars(self):
        test_cases = [
            ("Straßenbahn", "straxdfenbahn"),
            ("Спорт!", "u0421u043fu043eu0440u0442"),
            ("〔山脈〕", "u5c71u8108"),
        ]

        for (original, expected_result) in test_cases:
            self.assertEqual(cautious_slugify(original), expected_result)
예제 #7
0
    def test_escapes_non_latin_chars(self):
        test_cases = [
            ('Straßenbahn', 'straxdfenbahn'),
            ('Спорт!', 'u0421u043fu043eu0440u0442'),
            ('〔山脈〕', 'u5c71u8108'),
        ]

        for (original, expected_result) in test_cases:
            self.assertEqual(cautious_slugify(original), expected_result)
예제 #8
0
    def get(self, *args, **kwargs):
        pages = self.request.site.root_page.get_descendants()
        ids = []
        for page in pages:
            ids.append(page.id)
        form = get_object_or_404(
            MoloFormPage, slug=kwargs['slug'], id__in=ids)
        # Get information about form fields
        data_fields = [
            (field.clean_name, field.label)
            for field in form.get_form_fields()
        ]

        results = dict()
        # Get all submissions for current page
        submissions = (
            form.get_submission_class().objects.filter(page=form))
        for submission in submissions:
            data = submission.get_data()

            # Count results for each question
            for name, label in data_fields:
                answer = data.get(name)
                if answer is None:
                    # Something wrong with data.
                    # Probably you have changed questions
                    # and now we are receiving answers for old questions.
                    # Just skip them.
                    continue

                if type(answer) is list:
                    # answer is a list if the field type is 'Checkboxes'
                    answer = u', '.join(answer)

                question_stats = results.get(label, {})
                question_stats[cautious_slugify(answer)] = \
                    question_stats.get(cautious_slugify(answer), 0) + 1
                results[label] = question_stats

        for question, answers in results.items():
            total = sum(answers.values())
            for key in answers.keys():
                answers[key] = int(round((answers[key] * 100) / total))
        return JsonResponse(results)
예제 #9
0
def get_segment_location_info(source_instance, tab_helper, segment):
    context = segment.context
    context_path_components = context.path.split('.')
    field = segment.source.specific_content_type.model_class()._meta.get_field(
        context_path_components[0])

    # Work out which tab the segment is on from edit handler
    tab = cautious_slugify(tab_helper.get_field_tab(field.name))

    if isinstance(field, StreamField):
        stream_value = field.value_from_object(source_instance)
        stream_blocks_by_id = {
            block.id: block
            for block in field.value_from_object(source_instance)
        }
        block_id = context_path_components[1]
        block_value = stream_blocks_by_id[block_id]
        block_type = stream_value.stream_block.child_blocks[
            block_value.block_type]

        if isinstance(block_type, StructBlock):
            block_field_name = context_path_components[2]
            block_field = block_type.child_blocks[block_field_name].label
        else:
            block_field = None

        return {
            'tab': tab,
            'field': capfirst(block_type.label),
            'blockId': block_id,
            'fieldHelpText': '',
            'subField': block_field,
        }

    elif (isinstance(field, (models.ManyToOneRel))
          and isinstance(field.remote_field, ParentalKey)
          and issubclass(field.related_model, TranslatableMixin)):
        child_field = field.related_model._meta.get_field(
            context_path_components[2])

        return {
            'tab': tab,
            'field': capfirst(field.related_model._meta.verbose_name),
            'blockId': context_path_components[1],
            'fieldHelpText': child_field.help_text,
            'subField': capfirst(child_field.verbose_name),
        }

    else:
        return {
            'tab': tab,
            'field': capfirst(field.verbose_name),
            'blockId': None,
            'fieldHelpText': field.help_text,
            'subField': None,
        }
예제 #10
0
    def test_behaves_same_as_slugify_for_latin_chars(self):
        test_cases = [
            ('', ''),
            ('???', ''),
            ('Hello world', 'hello-world'),
            ('Hello_world', 'hello_world'),
            ('Hellö wörld', 'hello-world'),
            ('Hello   world', 'hello-world'),
            ('   Hello world   ', 'hello-world'),
            ('Hello, world!', 'hello-world'),
            ('Hello*world', 'helloworld'),
            ('Hello☃world', 'helloworld'),
        ]

        for (original, expected_result) in test_cases:
            self.assertEqual(slugify(original), expected_result)
            self.assertEqual(cautious_slugify(original), expected_result)
예제 #11
0
파일: test_utils.py 프로젝트: jams2/wagtail
    def test_behaves_same_as_slugify_for_latin_chars(self):
        test_cases = [
            ("", ""),
            ("???", ""),
            ("Hello world", "hello-world"),
            ("Hello_world", "hello_world"),
            ("Hellö wörld", "hello-world"),
            ("Hello   world", "hello-world"),
            ("   Hello world   ", "hello-world"),
            ("Hello, world!", "hello-world"),
            ("Hello*world", "helloworld"),
            ("Hello☃world", "helloworld"),
        ]

        for (original, expected_result) in test_cases:
            self.assertEqual(slugify(original), expected_result)
            self.assertEqual(cautious_slugify(original), expected_result)
예제 #12
0
    def test_behaves_same_as_slugify_for_latin_chars(self):
        test_cases = [
            ('', ''),
            ('???', ''),
            ('Hello world', 'hello-world'),
            ('Hello_world', 'hello_world'),
            ('Hellö wörld', 'hello-world'),
            ('Hello   world', 'hello-world'),
            ('   Hello world   ', 'hello-world'),
            ('Hello, world!', 'hello-world'),
            ('Hello*world', 'helloworld'),
            ('Hello☃world', 'helloworld'),
        ]

        for (original, expected_result) in test_cases:
            self.assertEqual(slugify(original), expected_result)
            self.assertEqual(cautious_slugify(original), expected_result)
예제 #13
0
파일: menu.py 프로젝트: mixxorz/wagtail
    def __init__(self,
                 label,
                 url,
                 name=None,
                 classnames='',
                 icon_name='',
                 attrs=None,
                 order=1000):
        self.label = label
        self.url = url
        self.classnames = classnames
        self.icon_name = icon_name
        self.name = (name or cautious_slugify(str(label)))
        self.order = order

        if attrs:
            self.attr_string = flatatt(attrs)
        else:
            self.attr_string = ""
예제 #14
0
def generate_slug(text, tail_number=0):
    from wagtail.core.models import Page
    """
    Returns a new unique slug. Object must provide a SlugField called slug.
    URL friendly slugs are generated using django.template.defaultfilters'
    slugify. Numbers are added to the end of slugs for uniqueness.

    based on implementation in jmbo.utils
    https://github.com/praekelt/jmbo/blob/develop/jmbo/utils/__init__.py
    """

    # Empty slugs are ugly (eg. '-1' may be generated) so force non-empty
    if not text:
        text = 'no-title'

    # use django slugify filter to slugify
    slug = cautious_slugify(text)[:255]

    values_list = Page.objects.filter(slug__startswith=slug).values_list(
        'id', 'slug')

    # Find highest suffix
    max = -1
    for tu in values_list:
        if tu[1] == slug:
            if max == -1:
                # Set max to indicate a collision
                max = 0

        # Update max if suffix is greater
        match = RE_NUMERICAL_SUFFIX.match(tu[1])
        if match is not None:
            i = int(match.group(1))
            if i > max:
                max = i

    if max >= 0:
        # There were collisions
        return "%s-%s" % (slug, max + 1)
    else:
        # No collisions
        return slug
예제 #15
0
def get_segment_location_info(
    source_instance, tab_helper, content_path, field_path, widget=False
):
    content_path_components = content_path.split(".")
    field_path_components = field_path.split(".")
    field = source_instance._meta.get_field(field_path_components[0])

    # Work out which tab the segment is on from edit handler
    try:
        tab = cautious_slugify(tab_helper.get_field_tab(field.name))
    except KeyError:
        raise FieldHasNoEditPanelError

    order = tab_helper.get_field_order(field.name)

    def widget_from_field(field):
        if isinstance(field, models.ForeignKey):
            if issubclass(field.related_model, Page):
                edit_handler = tab_helper.get_field_edit_handler(field.name)

                if isinstance(edit_handler, PageChooserPanel):
                    return {
                        "type": "page_chooser",
                        "allowed_page_types": [
                            "{app}.{model}".format(
                                app=model._meta.app_label, model=model._meta.model_name
                            )
                            for model in edit_handler.target_models()
                        ],
                    }

                else:
                    return {"type": "unknown"}

            elif issubclass(field.related_model, AbstractDocument):
                return {"type": "document_chooser"}

            elif issubclass(field.related_model, AbstractImage):
                return {"type": "image_chooser"}

            elif issubclass(field.related_model, tuple(get_snippet_models())):
                return {
                    "type": "snippet_chooser",
                    "snippet_model": {
                        "app_label": field.related_model._meta.app_label,
                        "model_name": field.related_model._meta.model_name,
                        "verbose_name": field.related_model._meta.verbose_name,
                        "verbose_name_plural": field.related_model._meta.verbose_name_plural,
                    },
                    "chooser_url": reverse(
                        "wagtailsnippets:choose",
                        args=[
                            field.related_model._meta.app_label,
                            field.related_model._meta.model_name,
                        ],
                    ),
                }

        elif isinstance(
            field,
            (models.CharField, models.TextField, models.EmailField, models.URLField),
        ):
            return {
                "type": "text",
            }

        return {"type": "unknown"}

    def widget_from_block(block, content_components=None):
        if isinstance(block, blocks.PageChooserBlock):
            return {
                "type": "page_chooser",
                "allowed_page_types": [
                    "{app}.{model}".format(
                        app=model._meta.app_label, model=model._meta.model_name
                    )
                    # Note: Unlike PageChooserPanel, the block doesn't automatically fall back to [Page]
                    for model in block.target_models or [Page]
                ],
            }

        elif isinstance(block, DocumentChooserBlock):
            return {"type": "document_chooser"}

        elif isinstance(block, ImageChooserBlock):
            return {"type": "image_chooser"}

        elif isinstance(block, SnippetChooserBlock):
            return {
                "type": "snippet_chooser",
                "snippet_model": {
                    "app_label": block.target_model._meta.app_label,
                    "model_name": block.target_model._meta.model_name,
                    "verbose_name": block.target_model._meta.verbose_name,
                    "verbose_name_plural": block.target_model._meta.verbose_name_plural,
                },
                "chooser_url": reverse(
                    "wagtailsnippets:choose",
                    args=[
                        block.target_model._meta.app_label,
                        block.target_model._meta.model_name,
                    ],
                ),
            }

        elif isinstance(
            block,
            (
                blocks.CharBlock,
                blocks.TextBlock,
                blocks.RichTextBlock,
                blocks.EmailBlock,
                blocks.URLBlock,
            ),
        ):
            return {
                "type": "text",
            }
        elif (
            isinstance(block, blocks.StructBlock)
            and content_components
            and isinstance(content_components, list)
        ):
            block_field_name = content_components.pop(0)
            return widget_from_block(
                block.child_blocks.get(block_field_name), content_components
            )

        return {"type": "unknown"}

    if isinstance(field, StreamField):
        block_type_name = field_path_components[1]
        block_type = field.stream_block.child_blocks[block_type_name]

        if isinstance(block_type, blocks.StructBlock):
            block_field_name = field_path_components[2]
            block_field = block_type.child_blocks[block_field_name].label

        else:
            block_field = None

        return {
            "tab": tab,
            "field": capfirst(block_type.label),
            "order": order,
            "blockId": content_path_components[1],
            "fieldHelpText": "",
            "subField": block_field,
            "widget": widget_from_block(block_type, content_path_components[2:])
            if widget
            else None,
        }

    elif (
        isinstance(field, (models.ManyToOneRel))
        and isinstance(field.remote_field, ParentalKey)
        and issubclass(field.related_model, TranslatableMixin)
    ):
        child_field = field.related_model._meta.get_field(field_path_components[1])

        return {
            "tab": tab,
            "field": capfirst(field.related_model._meta.verbose_name),
            "order": order,
            "blockId": content_path_components[1],
            "fieldHelpText": child_field.help_text,
            "subField": capfirst(child_field.verbose_name),
            "widget": widget_from_field(child_field) if widget else None,
        }

    else:
        return {
            "tab": tab,
            "field": capfirst(field.verbose_name),
            "order": order,
            "blockId": None,
            "fieldHelpText": field.help_text,
            "subField": None,
            "widget": widget_from_field(field) if widget else None,
        }
예제 #16
0
def get_segment_location_info(source_instance,
                              tab_helper,
                              content_path,
                              widget=False):
    context_path_components = content_path.split('.')
    field = source_instance._meta.get_field(context_path_components[0])

    # Work out which tab the segment is on from edit handler
    tab = cautious_slugify(tab_helper.get_field_tab(field.name))

    def widget_from_field(field):
        if isinstance(field, models.ForeignKey):
            if issubclass(field.related_model, Page):
                # TODO: Allowed page types
                return {'type': 'page_chooser'}

            elif issubclass(field.related_model, AbstractDocument):
                return {'type': 'document_chooser'}

            elif issubclass(field.related_model, AbstractImage):
                return {'type': 'image_chooser'}

        elif isinstance(field, (models.CharField, models.TextField,
                                models.EmailField, models.URLField)):
            return {
                'type': 'text',
            }

        return {'type': 'unknown'}

    def widget_from_block(block):
        # TODO: Snippet chooser block
        if isinstance(block, blocks.PageChooserBlock):
            # TODO: Allowed page types
            return {'type': 'page_chooser'}

        elif isinstance(block, DocumentChooserBlock):
            return {'type': 'document_chooser'}

        elif isinstance(block, ImageChooserBlock):
            return {'type': 'image_chooser'}

        elif isinstance(block, (blocks.CharBlock, blocks.TextBlock,
                                blocks.EmailBlock, blocks.URLBlock)):
            return {
                'type': 'text',
            }

        return {'type': 'unknown'}

    if isinstance(field, StreamField):
        stream_value = field.value_from_object(source_instance)
        stream_blocks_by_id = {
            block.id: block
            for block in field.value_from_object(source_instance)
        }
        block_id = context_path_components[1]
        block_value = stream_blocks_by_id[block_id]
        block_type = stream_value.stream_block.child_blocks[
            block_value.block_type]

        if isinstance(block_type, blocks.StructBlock):
            block_field_name = context_path_components[2]
            block_field = block_type.child_blocks[block_field_name].label
        else:
            block_field = None

        return {
            'tab': tab,
            'field': capfirst(block_type.label),
            'blockId': block_id,
            'fieldHelpText': '',
            'subField': block_field,
            'widget': widget_from_block(block_type) if widget else None,
        }

    elif (isinstance(field, (models.ManyToOneRel))
          and isinstance(field.remote_field, ParentalKey)
          and issubclass(field.related_model, TranslatableMixin)):
        child_field = field.related_model._meta.get_field(
            context_path_components[2])

        return {
            'tab': tab,
            'field': capfirst(field.related_model._meta.verbose_name),
            'blockId': context_path_components[1],
            'fieldHelpText': child_field.help_text,
            'subField': capfirst(child_field.verbose_name),
            'widget': widget_from_field(child_field) if widget else None,
        }

    else:
        return {
            'tab': tab,
            'field': capfirst(field.verbose_name),
            'blockId': None,
            'fieldHelpText': field.help_text,
            'subField': None,
            'widget': widget_from_field(field) if widget else None,
        }
예제 #17
0
 def tabs_with_slugs(self):
     return [{
         'label': label,
         'slug': cautious_slugify(label),
     } for label in self.tabs]
예제 #18
0
def get_segment_location_info(source_instance,
                              tab_helper,
                              content_path,
                              widget=False):
    context_path_components = content_path.split('.')
    field = source_instance._meta.get_field(context_path_components[0])

    # Work out which tab the segment is on from edit handler
    try:
        tab = cautious_slugify(tab_helper.get_field_tab(field.name))
    except KeyError:
        raise FieldHasNoEditPanelError

    order = tab_helper.get_field_order(field.name)

    def widget_from_field(field):
        if isinstance(field, models.ForeignKey):
            if issubclass(field.related_model, Page):
                edit_handler = tab_helper.get_field_edit_handler(field.name)

                if isinstance(edit_handler, PageChooserPanel):
                    return {
                        'type':
                        'page_chooser',
                        'allowed_page_types': [
                            '{app}.{model}'.format(
                                app=model._meta.app_label,
                                model=model._meta.model_name)
                            for model in edit_handler.target_models()
                        ],
                    }

                else:
                    return {'type': 'unknown'}

            elif issubclass(field.related_model, AbstractDocument):
                return {'type': 'document_chooser'}

            elif issubclass(field.related_model, AbstractImage):
                return {'type': 'image_chooser'}

            elif issubclass(field.related_model, tuple(get_snippet_models())):
                return {
                    'type':
                    'snippet_chooser',
                    'snippet_model': {
                        'app_label':
                        field.related_model._meta.app_label,
                        'model_name':
                        field.related_model._meta.model_name,
                        'verbose_name':
                        field.related_model._meta.verbose_name,
                        'verbose_name_plural':
                        field.related_model._meta.verbose_name_plural,
                    },
                    'chooser_url':
                    reverse('wagtailsnippets:choose',
                            args=[
                                field.related_model._meta.app_label,
                                field.related_model._meta.model_name
                            ])
                }

        elif isinstance(field, (models.CharField, models.TextField,
                                models.EmailField, models.URLField)):
            return {
                'type': 'text',
            }

        return {'type': 'unknown'}

    def widget_from_block(block):
        if isinstance(block, blocks.PageChooserBlock):
            return {
                'type':
                'page_chooser',
                'allowed_page_types': [
                    '{app}.{model}'.format(app=model._meta.app_label,
                                           model=model._meta.model_name)

                    # Note: Unlike PageChooserPanel, the block doesn't automatically fall back to [Page]
                    for model in block.target_models or [Page]
                ]
            }

        elif isinstance(block, DocumentChooserBlock):
            return {'type': 'document_chooser'}

        elif isinstance(block, ImageChooserBlock):
            return {'type': 'image_chooser'}

        elif isinstance(block, SnippetChooserBlock):
            return {
                'type':
                'snippet_chooser',
                'snippet_model': {
                    'app_label':
                    block.target_model._meta.app_label,
                    'model_name':
                    block.target_model._meta.model_name,
                    'verbose_name':
                    block.target_model._meta.verbose_name,
                    'verbose_name_plural':
                    block.target_model._meta.verbose_name_plural,
                },
                'chooser_url':
                reverse('wagtailsnippets:choose',
                        args=[
                            block.target_model._meta.app_label,
                            block.target_model._meta.model_name
                        ])
            }

        elif isinstance(
                block,
            (blocks.CharBlock, blocks.TextBlock, blocks.RichTextBlock,
             blocks.EmailBlock, blocks.URLBlock)):
            return {
                'type': 'text',
            }

        return {'type': 'unknown'}

    if isinstance(field, StreamField):
        stream_value = field.value_from_object(source_instance)
        stream_blocks_by_id = {
            block.id: block
            for block in field.value_from_object(source_instance)
        }
        block_id = context_path_components[1]
        block_value = stream_blocks_by_id[block_id]
        block_type = stream_value.stream_block.child_blocks[
            block_value.block_type]

        if isinstance(block_type, blocks.StructBlock):
            block_field_name = context_path_components[2]
            block_field = block_type.child_blocks[block_field_name].label
        else:
            block_field = None

        return {
            'tab': tab,
            'field': capfirst(block_type.label),
            'order': order,
            'blockId': block_id,
            'fieldHelpText': '',
            'subField': block_field,
            'widget': widget_from_block(block_type) if widget else None,
        }

    elif (isinstance(field, (models.ManyToOneRel))
          and isinstance(field.remote_field, ParentalKey)
          and issubclass(field.related_model, TranslatableMixin)):
        child_field = field.related_model._meta.get_field(
            context_path_components[2])

        return {
            'tab': tab,
            'field': capfirst(field.related_model._meta.verbose_name),
            'order': order,
            'blockId': context_path_components[1],
            'fieldHelpText': child_field.help_text,
            'subField': capfirst(child_field.verbose_name),
            'widget': widget_from_field(child_field) if widget else None,
        }

    else:
        return {
            'tab': tab,
            'field': capfirst(field.verbose_name),
            'order': order,
            'blockId': None,
            'fieldHelpText': field.help_text,
            'subField': None,
            'widget': widget_from_field(field) if widget else None,
        }