def test_all_models_cached(): exclude = { # apps components.models.ComponentsApp, find_a_supplier.models.FindASupplierApp, invest.models.InvestApp, # "folders" export_readiness.models.MarketingPages, export_readiness.models.SitePolicyPages, export_readiness.models.ContactUsGuidancePages, export_readiness.models.ContactSuccessPages, export_readiness.models.EUExitFormPages, export_readiness.models.AllContactPagesPage, great_international.models.InternationalRegionPage, great_international.models.InternationalLocalisedFolderPage, # Page is added by TestSubscriber in other tests. Page, } all_models = { model for model in get_page_models() if model not in exclude } cached_models = { item.model for item in cache.AbstractDatabaseCacheSubscriber.__subclasses__() if item.model not in exclude } assert all_models == cached_models
def post(self, request): form = ExternalLinksForm(request.POST) if not form.is_valid(): return render(request, self.template_name, {'form': form}) url = form.cleaned_data['url'] pages = [] for cls in get_page_models(): pages += list(cls.objects.search(url)) pages = self.remove_duplicates(pages) pages = sorted(pages, key=lambda k: k.title) contacts = list(Contact.objects.filter(body__contains=url)) resources = sorted( list(Resource.objects.filter(link__contains=url)) + list(Resource.objects.filter(alternate_link__contains=url)), key=lambda k: k.title) reusable_texts = list( ReusableText.objects.filter(text__contains=url).order_by('title')) num_page_results = len(pages) num_snippet_results = len(contacts + resources + reusable_texts) return render( request, self.template_name, { 'form': form, 'pages': pages, 'contacts': contacts, 'resources': resources, 'reusable_texts': reusable_texts, 'num_page_results': num_page_results, 'num_snippet_results': num_snippet_results, })
def handle(self, *args, **options): from_text = options['from_text'] to_text = options['to_text'] for revision in PageRevision.objects.filter( content_json__contains=from_text): revision.content_json = revision.content_json.replace( from_text, to_text) revision.save(update_fields=['content_json']) for page_class in get_page_models(): self.stdout.write("scanning %s" % page_class._meta.verbose_name) child_relation_names = [ rel.get_accessor_name() for rel in get_all_child_relations(page_class) ] # Find all pages of this exact type; exclude subclasses, as they will # appear in the get_page_models() list in their own right, and this # ensures that replacement happens only once for page in page_class.objects.exact_type(page_class): replace_in_model(page, from_text, to_text) for child_rel in child_relation_names: for child in getattr(page, child_rel).all(): replace_in_model(child, from_text, to_text)
def share_signal(sender, **kwargs): # First check if app is in debug mode # and if we should perform sharing during # debug. Defaults to False share_in_debug = get_setting("SHARE_IN_DEBUG", required=False) or False if settings.DEBUG and not share_in_debug: return # Check if the sender is a subclass of 'SocialMediaSharablePageMixin' if not issubclass(sender, SocialMediaSharablePageMixin): # If the sender does not inherit the mixin, it should not be shared. return # Check if sender is a registered Wagtail Page if not sender in get_page_models(): return # Get page instance instance = kwargs["instance"] # Check if page was already shared if instance.was_shared: return # Share the page share_page(instance)
def get_story_page_models(): """ Return a list of all non-abstract page models that inherit from BaseWebStoryPage """ return [ model for model in get_page_models() if issubclass(model, BaseWebStoryPage) ]
def panel_type_check(app_configs, **kwargs): from wagtail.core.models import get_page_models errors = [] for cls in get_page_models(): errors += traverse_edit_handlers(cls.get_edit_handler()) return errors
def generate_graphene_objects_for_all_page_types(): models = get_page_models() graphene_objects = [] for model in models: graphene_object = type( f'{model.__name__}', (DjangoObjectType, ), {'Meta': type('Meta', (object, ), {'model': model})}) graphene_objects.append(graphene_object) return graphene_objects
def get_form_types(): global _FORM_CONTENT_TYPES if _FORM_CONTENT_TYPES is None: form_models = [ model for model in get_page_models() if issubclass(model, AbstractForm) ] _FORM_CONTENT_TYPES = list( ContentType.objects.get_for_models(*form_models).values()) return _FORM_CONTENT_TYPES
def get_survey_types(): global _FORM_CONTENT_TYPES if _FORM_CONTENT_TYPES is None: form_models = [ model for model in get_page_models() if issubclass(model, AbstractSurvey) ] _FORM_CONTENT_TYPES = list( ContentType.objects.get_for_models(*form_models).values() ) return _FORM_CONTENT_TYPES
def unregister_signal_handlers(): Image = get_image_model() Document = get_document_model() for model in get_page_models(): page_published.disconnect(purge_page_from_cache, sender=model) page_unpublished.disconnect(purge_page_from_cache, sender=model) post_save.disconnect(purge_image_from_cache, sender=Image) post_delete.disconnect(purge_image_from_cache, sender=Image) post_save.disconnect(purge_document_from_cache, sender=Document) post_delete.disconnect(purge_document_from_cache, sender=Document)
def resolve_models(self): """ Find all Wagtail page models eligible to be in the GraphQL endpoint. They need to subclass :class:`wagtail_graphql.models.GraphQLEnabledModel`. """ for model in get_page_models(): assert model not in self._models # Check if the page model is GraphQL enabled if issubclass(model, GraphQLEnabledModel) or model is Page: self._models.add(model) self.resolve_model_fields_for(model)
def get_form_types(): global _FORM_CONTENT_TYPES if _FORM_CONTENT_TYPES is None: from wagtail.contrib.forms.models import AbstractForm form_models = [ model for model in get_page_models() if issubclass(model, AbstractForm) ] _FORM_CONTENT_TYPES = list( ContentType.objects.get_for_models(*form_models).values() ) return _FORM_CONTENT_TYPES
def inline_panel_model_panels_check(app_configs, **kwargs): from wagtail.core.models import get_page_models errors = [] page_models = get_page_models() for cls in page_models: errors.extend(check_panels_in_model(cls)) # filter out duplicate errors found for the same model unique_errors = [] for error in errors: if error.msg not in [e.msg for e in unique_errors]: unique_errors.append(error) return unique_errors
def _clear_edit_handler_cache(self): """ These tests generate new EditHandlers with different settings. The cached edit handlers should be cleared before and after each test run to ensure that no changes leak through to other tests. """ from wagtail.tests.testapp.models import DefaultRichBlockFieldPage rich_text_block = (DefaultRichBlockFieldPage.get_edit_handler( ).get_form_class().base_fields['body'].block.child_blocks['rich_text']) if hasattr(rich_text_block, 'field'): del rich_text_block.field for page_class in get_page_models(): page_class.get_edit_handler.cache_clear()
def _clear_edit_handler_cache(self): """ These tests generate new EditHandlers with different settings. The cached edit handlers should be cleared before and after each test run to ensure that no changes leak through to other tests. """ from wagtail.tests.testapp.models import DefaultRichBlockFieldPage rich_text_block = (DefaultRichBlockFieldPage.get_edit_handler() .get_form_class().base_fields['body'].block .child_blocks['rich_text']) if hasattr(rich_text_block, 'field'): del rich_text_block.field for page_class in get_page_models(): page_class.get_edit_handler.cache_clear()
def get_page_type_choices(): choices = [] for m in get_page_models(): choice = (ContentType.objects.get_for_model(m).id, m.get_verbose_name()) if m is Page: page_choice = choice else: choices.append(choice) # sort by model verbose name choices.sort(key=lambda c: c[1]) # HACK: put Page first so it will appear as default # Using initial won't work because the form is always bound in the views choices.insert(0, page_choice) return choices
def get_form_class_check(app_configs, **kwargs): from wagtail.admin.forms import WagtailAdminPageForm from wagtail.core.models import get_page_models errors = [] for cls in get_page_models(): edit_handler = cls.get_edit_handler() if not issubclass(edit_handler.get_form_class(), WagtailAdminPageForm): errors.append(Error( "{cls}.get_edit_handler().get_form_class() does not extend WagtailAdminPageForm".format( cls=cls.__name__), hint="Ensure that the EditHandler for {cls} creates a subclass of WagtailAdminPageForm".format( cls=cls.__name__), obj=cls, id='wagtailadmin.E002')) return errors
def base_form_class_check(app_configs, **kwargs): from wagtail.admin.forms import WagtailAdminPageForm from wagtail.core.models import get_page_models errors = [] for cls in get_page_models(): if not issubclass(cls.base_form_class, WagtailAdminPageForm): errors.append(Error( "{}.base_form_class does not extend WagtailAdminPageForm".format( cls.__name__), hint="Ensure that {}.{} extends WagtailAdminPageForm".format( cls.base_form_class.__module__, cls.base_form_class.__name__), obj=cls, id='wagtailadmin.E001')) return errors
def codered_forms(user, editable_forms): from coderedcms.models import CoderedFormMixin """ Add our own CoderedFormPage to editable_forms, since wagtail is unaware of its existence. Essentially this is a fork of wagtail.contrib.forms.get_forms_for_user() and wagtail.contrib.forms.get_form_types() """ form_models = [ model for model in get_page_models() if issubclass(model, CoderedFormMixin) ] form_types = list( ContentType.objects.get_for_models(*form_models).values()) editable_forms = UserPagePermissionsProxy(user).editable_pages() editable_forms = editable_forms.filter(content_type__in=form_types) return editable_forms
def get_page_models_using_blocks( block_types: Union[Type[Block], Tuple[Type[Block]]], ) -> Dict[Type[Model], List[ModelStreamFieldBlockInfo]]: """Returns information about all page models which use the specified block type(s) in a StreamField.""" models_with_block: Dict[Type[Model], List[ModelStreamFieldBlockInfo]] = {} for page_model in get_page_models(): for stream_field in [ field for field in page_model._meta.get_fields() if isinstance(field, StreamField) ]: for stream_field_block in get_stream_field_blocks(stream_field): if isinstance(stream_field_block.block_type, block_types): if page_model not in models_with_block: models_with_block[page_model] = [] models_with_block[page_model].append( ModelStreamFieldBlockInfo(stream_field.attname, *stream_field_block), ) return models_with_block
def register_signal_handlers(): """Registers signal handlers. To create a signal for TranslatablePage we have to use wagtails get_page_model. """ post_save.connect(create_language_permissions_and_group, sender=Language) init_new_page.connect(force_parent_language) if get_wagtailtrans_setting('SYNC_TREE'): if get_wagtailtrans_setting('LANGUAGES_PER_SITE'): m2m_changed.connect(update_language_trees_for_site, sender=SiteLanguages.other_languages.through) else: post_save.connect(create_new_language_tree, sender=Language) for model in get_page_models(): if hasattr(model, 'create_translation'): post_save.connect(synchronize_trees, sender=model) if hasattr(model, 'get_translations'): pre_delete.connect(synchronize_deletions, sender=model)
def handle(self, *args, **options): from_text = options['from_text'] to_text = options['to_text'] for revision in PageRevision.objects.filter(content_json__contains=from_text): revision.content_json = revision.content_json.replace(from_text, to_text) revision.save(update_fields=['content_json']) for page_class in get_page_models(): self.stdout.write("scanning %s" % page_class._meta.verbose_name) child_relation_names = [rel.get_accessor_name() for rel in get_all_child_relations(page_class)] # Find all pages of this exact type; exclude subclasses, as they will # appear in the get_page_models() list in their own right, and this # ensures that replacement happens only once for page in page_class.objects.exact_type(page_class): replace_in_model(page, from_text, to_text) for child_rel in child_relation_names: for child in getattr(page, child_rel).all(): replace_in_model(child, from_text, to_text)
def page_search_fields_check(app_configs, **kwargs): """Checks each page model with search_fields to core fields are included""" from wagtail.core.models import Page, get_page_models page_models = get_page_models() errors = [] for cls in page_models: # Only checks an initial subset of fields as only need to check some are missing to show the warning if not all(field in cls.search_fields for field in Page.search_fields[:10]): errors.append( Warning( 'Core Page fields missing in `search_fields`', hint=' '.join([ 'Ensure that {} extends the Page model search fields', '`search_fields = Page.search_fields + [...]`' ]).format(cls.__name__), obj=cls, id='wagtailsearch.W001')) return errors
def get_content_types_for_filter(): models = [model.__name__.lower() for model in get_page_models()] return ContentType.objects.filter(model__in=models).order_by("model")
def register_signal_handlers(): for model in get_page_models(): page_published.connect(record_page_publish, sender=model)
def get_periodic_review_models(): from wagtail_periodic_review.models import PeriodicReviewMixin return [m for m in get_page_models() if issubclass(m, PeriodicReviewMixin)]