Exemplo n.º 1
0
def create_page(title="Test Title", parent=None, tags=[]):
    block = blocks.StructBlock([
        ("message", blocks.TextBlock()),
    ])
    block_value = block.to_python({"message": "test content WA"})
    contentpage = ContentPage(
        title=title,
        subtitle="Test Subtitle",
        body="The body",
        enable_whatsapp=True,
        whatsapp_title="WA Title",
        whatsapp_body=[
            ("Whatsapp_Message", block_value),
            ("Whatsapp_Message", block_value),
        ],
    )
    for tag in tags:
        created_tag, _ = Tag.objects.get_or_create(name=tag)
        contentpage.tags.add(created_tag)
    if parent:
        parent = ContentPage.objects.filter(title=parent)[0]
        parent.add_child(instance=contentpage)
    else:
        home_page = HomePage.objects.first()
        home_page.add_child(instance=contentpage)
    contentpage.save_revision()
    return contentpage
    def handle(self, *args, **options):
        def get_body(body_list):
            body = []
            for line in body_list:
                if len(line) != 0:
                    body = body + [("paragraph", RichText(line))]
            return body

        def create_tags(tags, page):
            for tag in tags:
                created_tag, _ = Tag.objects.get_or_create(name=tag)
                page.tags.add(created_tag)

        path = options["path"]
        home_page = HomePage.objects.first()
        with open(path) as json_file:
            data = json.load(json_file)
            for article in data["articles"]:
                contentpage = ContentPage(
                    title=article["title"],
                    subtitle=article["subtitle"],
                    body=get_body(article["body"]),
                )
                create_tags(article["tags"], contentpage)
                home_page.add_child(instance=contentpage)
                contentpage.save_revision()

            self.stdout.write(
                self.style.SUCCESS("Successfully imported Content Pages"))
Exemplo n.º 3
0
    def handle(self, *args, **options):
        def get_rich_text_body(row):
            body = []
            row = row.splitlines()
            for line in row:
                if len(line) != 0:
                    body = body + [("paragraph", RichText(line))]
            return body

        def get_text_body(raw):
            if options["splitmessages"] == "yes":
                struct_blocks = []
                if options["newline"]:
                    rows = raw.split(options["newline"])
                else:
                    rows = raw.splitlines()
                for row in rows:
                    if row:
                        block = blocks.StructBlock([
                            ("message", blocks.TextBlock()),
                        ])
                        block_value = block.to_python({"message": row})
                        struct_blocks.append(("Whatsapp_Message", block_value))
                return struct_blocks
            else:
                if raw:
                    block = blocks.StructBlock([
                        ("message", blocks.TextBlock()),
                    ])
                    block_value = block.to_python({"message": raw})
                    return [("Whatsapp_Message", block_value)]

        def create_tags(row, page):
            tags = row["tags"].split(",")
            for tag in tags:
                created_tag, _ = Tag.objects.get_or_create(name=tag.strip())
                page.tags.add(created_tag)

        def add_parent(row, page, home_page):
            if row["parent"]:
                parent = ContentPage.objects.filter(title=row["parent"])[0]
                parent.add_child(instance=page)
            else:
                home_page.add_child(instance=page)

        def clean_row(row):
            for field in (
                    "web_title",
                    "web_subtitle",
                    "web_body",
                    "whatsapp_title",
                    "whatsapp_body",
                    "parent",
            ):
                if row[field]:
                    row[field] = str(row[field]).strip()
            return row

        if options["purge"] == "yes":
            ContentPage.objects.all().delete()

        path = options["path"]
        home_page = HomePage.objects.first()
        with open(path, "rt") as f:
            reader = csv.DictReader(f)
            for row in reader:
                row = clean_row(row)
                contentpage = ContentPage(
                    title=row["web_title"],
                    subtitle=row["web_subtitle"],
                    body=get_rich_text_body(row["web_body"]),
                    enable_whatsapp=True,
                    whatsapp_title=row["whatsapp_title"],
                    whatsapp_body=get_text_body(row["whatsapp_body"]),
                )
                create_tags(row, contentpage)
                add_parent(row, contentpage, home_page)
                contentpage.save_revision().publish()

            self.stdout.write(
                self.style.SUCCESS("Successfully imported Content Pages"))
Exemplo n.º 4
0
    def handle(self, *args, **options):
        self.stdout.write('Creating development data... ', '')
        self.stdout.flush()

        # Delete the default home page
        Page.objects.get(slug='home').delete()

        # Basic setup
        root_page = Page.objects.get(title='Root')

        home_page = HomePage(
            title='Home',
            slug='home',
            main_title='Every news site should be secure.',
            sub_title='HTTPS encryption enables security, privacy, and '
                      'prevents censorship. We’re tracking its adoption.',
            why_header='HTTPS protects your privacy and security',
            why_body="With HTTPS enabled by default you can protect reader"
                     " privacy, improve your website's security, better"
                     " protect your sources, prevent censorship, improve"
                     " your search rankings, provide a better user experience,"
                     " see your website loading speeds potentially increase,"
                     " and avoid Google shaming.",
            how_header='Resources for switching your news site over to HTTPS',
            how_body="Switching your news site over to HTTPS is not as simple"
                     " as flicking a switch. But a handful of news "
                     "organizations have already pioneered the effort and "
                     "have shared their tips and tricks for making it as "
                     "smooth as possible. We've documented them here."
        )
        root_page.add_child(instance=home_page)

        site = Site.objects.create(
            site_name='Freedom of the Press (Dev)',
            hostname='localhost',
            port='8000',
            root_page=home_page,
            is_default_site=True
        )

        # Add "Why?" and "How" pages, since they're so prominently featured
        # on the home page.
        why_page = ContentPage(
            title='Why?',
            slug='why',
            sub_header='10 good reasons to switch your site to HTTPS',
            show_in_menus=True
        )
        home_page.add_child(instance=why_page)

        how_page = ContentPage(
            title='How',
            slug='how',
            sub_header='Resources and tips for deploying HTTPS by default',
            show_in_menus=True
        )
        home_page.add_child(instance=how_page)

        # Update the "learn more" links on home page now that we've created the
        # "How" and "Why" pages for them to link to.
        home_page.why_learn_more = why_page
        home_page.how_learn_more = how_page
        home_page.save()

        # Add a BlogIndexPage and an example BlogPost
        blog_index_page = BlogIndexPage(
            title='Blog',
            slug='blog',
            show_in_menus=True
        )
        home_page.add_child(instance=blog_index_page)

        blog_post = BlogPost(
            title='Test Blog Post',
            slug='test-blog-post',
            date=datetime.date.today(),
            byline='Dog with a Blog'
        )
        blog_index_page.add_child(instance=blog_post)

        # Main menu via wagtailmenus
        # Remember: Pages must have `show_in_menus=True` *and* a corresponding
        # MainMenuItem to show up
        main_menu = MainMenu.objects.create(site=site)

        why_menu_item = MainMenuItem.objects.create(  # noqa: F841
            menu=main_menu,
            link_text='Why?',
            link_page=why_page
        )
        how_menu_item = MainMenuItem.objects.create(  # noqa: F841
            menu=main_menu,
            link_text='How',
            link_page=how_page
        )
        blog_index_menu_item = MainMenuItem.objects.create(  # noqa: F841
            menu=main_menu,
            link_text='Blog',
            link_page=blog_index_page
        )

        # Load sites and scans from fixtures
        management.call_command('loaddata', 'dev.json')

        # Create superuser
        User.objects.create_superuser(
            'test',
            '*****@*****.**',
            'test',
        )
Exemplo n.º 5
0
    def handle(self, *args, **options):
        def get_body(message):
            if message["attachment_media_type"] == "image":
                im = ""
                title = message["attachment_media_object"]["filename"]
                try:
                    im = Image.objects.get(title=title).id
                except Exception:
                    http_res = requests.get(message["attachment_uri"])
                    image_file = ImageFile(BytesIO(http_res.content),
                                           name=title)
                    image = Image(title=title, file=image_file)
                    image.save()
                    im = image.id

                block = blocks.StructBlock([("message", blocks.TextBlock()),
                                            ("image", ImageChooserBlock())])
                block_value = block.to_python({
                    "message": message["answer"],
                    "image": im
                })
                return block_value
            else:
                block = blocks.StructBlock([
                    ("message", blocks.TextBlock()),
                ])
                block_value = block.to_python({"message": message["answer"]})
                return block_value

        #
        # def create_tags(tags, page):
        #     for tag in tags:
        #         created_tag, _ = Tag.objects.get_or_create(name=tag)
        #         page.tags.add(created_tag)

        path = options["path"]

        ContentPage.objects.all().delete()
        with open(path) as json_file:
            data = json.load(json_file)

            for message in data["data"]:
                try:
                    title_list = message["question"].strip().split(" ")
                    language = title_list[-1]
                    language = language[1:-1]
                    home_page = HomePage.objects.get(title__icontains=language)
                    just_title = " ".join(title_list[0:-1])

                    contentpage = ContentPage(
                        title=message["question"],
                        whatsapp_title=message["question"],
                        whatsapp_body=[("Whatsapp_Message", get_body(message))
                                       ],
                        locale=home_page.locale,
                    )
                    # create_tags(article["tags"], contentpage)
                    home_page.add_child(instance=contentpage)
                    contentpage.save_revision().publish()

                    translations = ContentPage.objects.filter(
                        title__icontains=just_title)
                    if translations:
                        translation = translations.first()
                        if translation.pk != contentpage.pk:
                            key = translation.translation_key
                            contentpage.translation_key = key
                            contentpage.save_revision().publish()
                except Exception as e:
                    print(e)

            self.stdout.write(
                self.style.SUCCESS("Successfully imported Content Pages"))
Exemplo n.º 6
0
def import_content_csv(file,
                       splitmessages=True,
                       newline=None,
                       purge=True,
                       locale="en"):
    def get_rich_text_body(row):
        body = []
        row = row.splitlines()
        for line in row:
            if len(line) != 0:
                body = body + [("paragraph", RichText(line))]
        return body

    def get_body(raw, image_title=None):
        struct_blocks = []
        if image_title:
            im = Image.objects.get(title=image_title).id
            block = blocks.StructBlock([
                ("image", ImageChooserBlock()),
            ])
            block_value = block.to_python({"image": im})
            struct_blocks.append(("Whatsapp_Message", block_value))
        if splitmessages:
            if newline:
                rows = raw.split(newline)
            else:
                rows = raw.splitlines()
            for row in rows:
                if row:
                    block = blocks.StructBlock([
                        ("message", blocks.TextBlock()),
                    ])
                    block_value = block.to_python({"message": row})
                    struct_blocks.append(("Whatsapp_Message", block_value))
            return struct_blocks
        else:
            if raw:
                block = blocks.StructBlock([
                    ("message", blocks.TextBlock()),
                ])
                block_value = block.to_python({"message": raw})
                struct_blocks.append(("Whatsapp_Message", block_value))
                return struct_blocks

    def create_tags(row, page):
        tags = row["translation_tag"].split(",")
        for tag in tags:
            created_tag, _ = Tag.objects.get_or_create(name=tag.strip())
            page.tags.add(created_tag)

    def add_parent(row, page, home_page):
        if row["parent"]:
            parent = ContentPage.objects.filter(title=row["parent"],
                                                locale=page.locale).last()
            parent.add_child(instance=page)
        else:
            home_page.add_child(instance=page)

    def clean_row(row):
        for field in (
                "web_title",
                "web_subtitle",
                "web_body",
                "whatsapp_title",
                "whatsapp_body",
                "parent",
        ):
            if row[field]:
                row[field] = str(row[field]).strip()
        return row

    home_page = HomePage.objects.get(locale__pk=locale.pk)
    csv_file = file.read().decode("utf-8")
    reader = csv.DictReader(io.StringIO(csv_file))
    for row in reader:
        row = clean_row(row)
        contentpage = ContentPage(
            title=row["web_title"],
            subtitle=row["web_subtitle"],
            body=get_rich_text_body(row["web_body"]),
            enable_whatsapp=True,
            whatsapp_title=row["whatsapp_title"],
            whatsapp_body=get_body(row["whatsapp_body"], row["image_name"]),
            locale=home_page.locale,
        )
        create_tags(row, contentpage)
        add_parent(row, contentpage, home_page)
        contentpage.save_revision().publish()
        try:
            pages = contentpage.tags.first().home_contentpagetag_items.all()
            for page in pages:
                if page.content_object.pk != contentpage.pk:
                    contentpage.translation_key = page.content_object.translation_key
                    contentpage.save_revision().publish()
        except Exception as e:
            print(e)