class ResourceFactory(factory.django.DjangoModelFactory): class Meta: model = Resource path = factory.Sequence( lambda n: u'00010{}'.format(n)) # from wagtailcore_pagerevision depth = 3 numchild = 0 title = 'Dummy Resource Page' slug = factory.LazyAttribute(lambda obj: slugify(obj.title)) live = True has_unpublished_changes = False show_in_menus = False search_description = '' go_live_at = '1995-02-07 12:00' expire_at = '1995-02-08 12:00' expired = False content_type = factory.SubFactory(ContentTypeFactory, app_label="resource", model="resource") locked = False latest_revision_created_at = '1995-02-07 12:00' first_published_at = '1995-02-07 12:00' language = 'en' embed_url = 'https://www.slideshare.net/slideshow/embed_code/23090740/' embed_thumbnail = '//cdn.slidesharecdn.com/ss_thumbnails/jayatighoshonspeculation-130617001506-phpapp02-thumbnail-4.jpg?cb=1371446113' content = [ ('authors', RichText('<p>XYZ</p>')), ('copyright', RichText( '<p>XYZ, Professor, Centre for Economic Studies and Planning</p><p>\u00a0</p>' )), ('focus', RichText( '<p>The 2008 global food price fluctuations -- especially the policies on bio-fuel and the neglect of agriculture.</p>' )), ('factoids', RichText( '<p>Lack of public investment in agriculture and agriculture research .</p>' )) ] @classmethod def _setup_next_sequence(cls): return getattr(cls, 'starting_sequence_num', 20) @factory.post_generation def categories(self, create, extracted, **kwargs): if not create: return if extracted: for category in extracted: self.categories.add(category)
def test_render(self): value = RichText('<p>Merry <a linktype="page" id="4">Christmas</a>!</p>') result = str(value) self.assertEqual( result, '<div class="rich-text"><p>Merry <a href="/events/christmas/">Christmas</a>!</p></div>' )
def process_item(self, item, spider): """Save articles in the database. This method is called for every item pipeline component. """ text_index = Page.objects.filter(title="Minitrue Index").first() slug_path = slugify(truncate_string(item["text"], 5, '')) blogtitle = truncate_string(item["text"], 8) blogpage = BlogPage() blogpage.tags.add('minitrue') blogpage.body = [ ('paragraph', RichText(item["text"])), # ('image', ImageChooserBlock()), #('articleIP', blocks.URLBlock(item["link"])), ('articleIP', json.dumps(item["link"]).strip("\"")), ] try: text_index.add_child(instance=BlogPage( title=blogtitle, slug=slug_path, intro=truncate_string(item["text"], 25), body=blogpage.body, tags=blogpage.tags, )) # try: # text_index.add_child(instance=BlogPage(title=blogtitle, # slug=slug_path, # intro = truncate_string(item["text"],25), # body = blogpage.body)) except ValidationError as err: print(str(err)) return item
def test_render(self): text = '<p>To the <a linktype="page" id="{}">moon</a>!</p>'.format( self.single_event_page.id) value = RichText(text) result = str(value) expected = ('<div class="rich-text"><p>To the <a href="' '/foo/pointless-suffix/">moon</a>!</p></div>') self.assertEqual(result, expected)
def convert_to_streamfield(apps, schema_editor): BlogPost = apps.get_model('blog', 'BlogPost') for post in BlogPost.objects.all(): if post.body.raw_text and not post.body: post.body = [ ('rich_text', RichText(post.body.raw_text)), ] post.save()
def convert_to_streamfield(apps, _): production_page_model = apps.get_model("productions", "ProductionPage") for page in production_page_model.objects.all(): if page.highlights.raw_text and not page.highlights: page.highlights = [ ('paragraph', RichText(page.highlights.raw_text)), ] page.save()
def get_slide_detail(album): response_data = {} response_data['slides'] = [] photographers = [] slide_photo_graphers = [] for slide in album.slides.all(): slide_photo_graphers.extend( map( lambda photographer_name: photographer_name.name.encode('UTF-8' ), slide.image.photographers.all())) photographers_of_album = list(set(slide_photo_graphers)) for index, slide in enumerate(album.slides.all(), start=0): slide_dict = dict([('type', 'image'), ('show_title', "True"), ('album_title', album.title)]) slide_dict['src'] = slide.image.file.url slide_dict['src_resized'] = slide.image.get_rendition('height-876').url block = blocks.RichTextBlock() description_value = RichText(slide.description) slide_dict['description'] = block.render(description_value) slide_dict['album_description'] = album.description slide_dict['url'] = album.get_absolute_url() slide_dict['slide_photographer'] = map( lambda photographer_name: photographer_name.name.encode('UTF-8'), slide.image.photographers.all()) if index == 0: slide_dict['slide_photographer'] = photographers_of_album print index photographers.extend(set(slide.image.photographers.all())) if album.first_published_at: published_date = datetime.datetime.strptime( str(album.first_published_at)[:10], "%Y-%m-%d") else: published_date = datetime.datetime.now() date = published_date.strftime('%d %b,%Y') slide_dict['image_captured_date'] = date image_location = slide.image.locations.first() slide_dict['slide_location'] = "%s, %s" % ( image_location.district, image_location.state) if image_location else '' slide_dict['track_id'] = slide.audio response_data['slides'].append(slide_dict) response_data['authors'] = [] for photographer in set(photographers): photographer_dict = dict([ ('type', 'inline'), ('show_title', "False"), ('name', photographer.name), ('bio', photographer.bio_en), ('twitter_username', photographer.twitter_handle), ('facebook_username', photographer.facebook_username), ('email', photographer.email), ('website', photographer.website), ('author_url', reverse('author-detail', kwargs={'slug': photographer.slug})) ]) response_data['authors'].append(photographer_dict) return JsonResponse(response_data)
def test_can_assign_as_list(self): self.json_body.body = [('rich_text', RichText("<h2>hello world</h2>"))] self.json_body.save() # the body should now be a stream consisting of a single rich_text block fetched_body = StreamModel.objects.get(id=self.json_body.id).body self.assertIsInstance(fetched_body, StreamValue) self.assertEqual(len(fetched_body), 1) self.assertIsInstance(fetched_body[0].value, RichText) self.assertEqual(fetched_body[0].value.source, "<h2>hello world</h2>")
def convert_to_streamfield(apps, schema_editor): ContentPage = apps.get_model('home', 'ContentPage') for page in ContentPage.objects.all(): # That page.body could be "false-y" yet have a raw_text attribute seems # weird; this is an intentional design choice by Wagtail meant to # simplify migrations from RichTextField to StreamField. if page.body.raw_text and not page.body: page.body = [ ('rich_text', RichText(page.body.raw_text)), ] page.save()
class GuidelinesPageFactory(factory.django.DjangoModelFactory): class Meta: model = GuidelinesPage django_get_or_create = ('title', ) path = "00010007000B" depth = 3 numchild = 0 title = "Guidelines Page" live = True has_unpublished_changes = False seo_title = " " show_in_menus = False search_description = " " go_live_at = '2011-10-24 12:43' expire_at = '2050-12-31 12:43' expired = False content_type = factory.SubFactory(ContentTypeFactory, app_label="core", model="guidelinespage") locked = False latest_revision_created_at = '2011-10-24 12:43' first_published_at = '2011-10-24 12:43' language = 'en' strap = "Writers, photographers, filmmakers and others" content = [ ('heading_title', 'Types of Articles and Other Content'), ('heading_content', RichText( '<p> Many different kinds of articles/writing go up on PARI. There are: </p>' )), ('sub_section_with_heading', { 'heading': 'Full-length feature', 'content': RichText( '<p> Ideally, these articles will be 1,000 words or less, on average.</p>' ) }) ]
def migrate_old_posts(): """ Converts all old posts from a simple page format to one Wagtail accepts """ # id=4 is the specific page ID for the news index page index = Page.objects.get(id=4).specific old_posts = Communication.objects.using('old_data').all().order_by('date') user = get_user_model().objects.get(id=1) for post in old_posts: if post.title: title = post.title else: title = 'Archived item from {date}'.format( date=date(post.date, 'D jS F Y')) slug = slugify('{title} - {rand}'.format( title=title, rand=int(round(time.time() * 1000)))) if len(post.text) > 512: intro = post.text[:512] + '...' else: intro = post.text page = BlogPage( search_description='', seo_title=title, show_in_menus=False, slug=slug, title=title, date=post.date, first_published_at=post.date, intro=linebreaks(intro), ) page.body.stream_data = [ ('paragraph', RichText('<p>{body}</p>'.format(body=linebreaks(post.text)))) ] page.tags.add(COMMS_DICT[post.type]) print('Restoring article from {date}'.format(date=post.date)) index.add_child(instance=page) revision = page.save_revision(user=user, submitted_for_moderation=False) revision.publish() page.save()
def setUp(self): ContentType = apps.get_model('contenttypes.ContentType') Site = apps.get_model('wagtailcore.Site') # Delete the default homepage Page.objects.get(id=2).delete() # Create content type for homepage model homepage_content_type, created = ContentType.objects.get_or_create( model='HomePage', app_label='tests') # Create a new homepage homepage = HomePage.objects.create( title="Homepage", slug='home', content_type=homepage_content_type, path='00010001', depth=1, url_path="/home-page", ) # Create a site with the new homepage set as the root site = Site.objects.create(hostname='localhost', root_page=homepage, is_default_site=True) RSSFeedsSettings.objects.create( site=site, feed_app_label='tests', feed_model_name='BlogStreamPage', feed_title='Test Feed', feed_link="https://example.com", feed_description="Test Description", feed_item_description_field="intro", feed_item_content_field="body", feed_image_in_content=True, feed_item_date_field='date', is_feed_item_date_field_datetime=False, ) # Create collection for image img_collection = Collection.objects.create(name="test", depth=1) # Create an image image = Image.objects.create( title="Test image", file=get_test_image_file(), collection=img_collection, ) blogpage_content_type, created = ContentType.objects.get_or_create( model='BlogPage', app_label='tests') # Create Blog Page BlogPage.objects.create( title="BlogPage", intro="Welcome to Blog", body="This is the body of blog", date="2016-06-30", slug='blog-post', url_path="/home-page/blog-post/", content_type=blogpage_content_type, feed_image=image, path='000100010002', depth=2, ) stream_blogpage_content_type, created = ContentType.objects.get_or_create( model='BlogStreamPage', app_label='tests') # Create Stream Field Blog Page stream_page = BlogStreamPage.objects.create( title="BlogStreamPage", intro="Welcome to Blog Stream Page", body= [('heading', 'foo'), ('paragraph', RichText( '<p>Rich text</p><div style="padding-bottom: 56.25%;"' + ' class="responsive-object"> <iframe width="480" height="270"' + ' src="https://www.youtube.com/embed/mSffkWuCkgQ?feature=oembed"' + ' frameborder="0" allowfullscreen=""></iframe>' + '<img alt="wagtail.jpg" height="500"' + ' src="/media/images/wagtail.original.jpg" width="1300">' + '</div>'))], date="2016-08-30", slug='blog-stream-post', url_path="/home-page/blog-stream-post/", content_type=stream_blogpage_content_type, feed_image=image, path='000100010003', depth=3, )
def convert_to_streamfield(apps, schema_editor): ArticlePage = apps.get_model("articles", "ArticlePage") for page in ArticlePage.objects.all(): if page.body.raw_text and not page.body: page.body = [('paragraph', RichText(page.body.raw_text))] page.save()
def value_from_form(self, value): # RichTextArea returns a source-HTML string; concert to a RichText object return RichText(value)
def convert_to_streamfield(apps, schema_editor): BlogPost = apps.get_model("blog", "BlogPost") for post in BlogPost.objects.all(): if post.content.raw_text and not post.content: post.content = [('paragraph', RichText(post.content.raw_text))] post.save()
def test_evaluate_value(self): value = RichText(None) self.assertFalse(value) value = RichText('<p>wagtail</p>') self.assertTrue(value)
def value_from_form(self, value): # Rich text editors return a source-HTML string; convert to a RichText object return RichText(value)
def get_default(self): if isinstance(self.meta.default, RichText): return self.meta.default else: return RichText(self.meta.default)
def convert_to_streamfield(apps, schema_editor): ResourcePage = apps.get_model("resources", "ResourcePage") for page in ResourcePage.objects.all(): if page.body.raw_text and not page.body: page.body = [('rich_text', RichText(page.body.raw_text))] page.save()
def convert_to_streamfield(apps, schema_editor): ReviewPage = apps.get_model("creditcards", "CreditCardReview") for page in ReviewPage.objects.all(): if page.body.raw_text and not page.body: page.body = [('paragraph', RichText(page.body.raw_text))] page.save()
def to_python(self, value): # convert a source-HTML string from the JSONish representation # to a RichText object return RichText(value)
def test_construct_with_none(self): value = RichText(None) self.assertEqual(value.source, '')
def migrate_events(): event_index = Page.objects.get(id=6).specific user = get_user_model().objects.get(id=1) old_events = OldEvent.objects.using('old_data').all() # Migrate events for old_event in old_events: old_event_type = old_event.type try: # We don't actually care about this - its a test to migrate the event across event_type = EventType.objects.get(name=old_event_type.name, target=old_event_type.target) except EventType.DoesNotExist: event_type = EventType(name=old_event_type.name, target=old_event_type.target) event_type.save() title = '{type} on {date}'.format(type=old_event_type.name, date=date(old_event.start, 'D jS F Y')) slug = slugify('{title} - {rand}'.format( title=title, rand=int(round(time.time() * 1000)))) if old_event.shortDescription: description = old_event.shortDescription else: if old_event_type.info: description = old_event_type.info else: description = old_event_type.name new_event = EventPage(title=title.strip(), slug=slug, description=description.strip(), start=old_event.start, finish=old_event.finish, cancelled=old_event.cancelled, category=event_type, location=old_event.location.name) new_event.body.stream_data = [ ('paragraph', RichText('<p>{body}</p>'.format( body=linebreaks(old_event.longDescription)))) ] print('Restoring event {type} from {date}'.format( type=old_event.type.name, date=old_event.start)) event_index.add_child(instance=new_event) revision = new_event.save_revision(user=user, submitted_for_moderation=False) revision.publish() new_event.save() # Deal with signups old_signups = Signup.objects.using('old_data').filter( event_id=old_event.id) for old_signup in old_signups: print('Restoring signup for {type} from {date}'.format( type=old_event.type.name, date=old_event.start)) new_signup = EventSignup( comment=truncatechars(old_signup.comment, 1024), member=get_user_model().objects.get(id=old_signup.user_id), event_id=new_event.id, signup_created=old_signup.time) new_signup.save()
def test_construct_with_empty_string(self): value = RichText('') self.assertEqual(value.source, '')
def test_construct_with_nonempty_string(self): value = RichText('<p>hello world</p>') self.assertEqual(value.source, '<p>hello world</p>')
def _convert_to_streamfield(apps, model_name): Model = apps.get_model("cms_pages", model_name) for page in Model.objects.all(): if page.body.raw_text and not page.body: page.body = [('rich_text', RichText(page.body.raw_text))] page.save()