def get_path(cls, instance): if isinstance(instance, Page): # Page paths have the format: `pages/URL_PATH` # Note: Page.url_path always starts with a '/' return "pages" + instance.url_path.rstrip("/") else: model_name = instance._meta.app_label + "." + instance.__class__.__name__ if isinstance(instance, tuple(get_snippet_models())): # Snippet paths have the format `snippets/app_label.ModelName/ID-title-slugified` base_path = "snippets/" + model_name elif isinstance(instance, AbstractImage): # Image paths have the format `images/ID-title-slugified` base_path = "images" elif isinstance(instance, AbstractDocument): # Document paths have the format `documents/ID-title-slugified` base_path = "documents" else: # All other models paths have the format `other/app_label.ModelName/ID-title-slugified` base_path = "other/" + model_name return base_path + "/" + str(instance.pk) + "-" + slugify( str(instance))
def index(request): snippet_model_opts = [ model._meta for model in get_snippet_models() if user_can_edit_snippet_type(request.user, model)] return render(request, 'wagtailsnippets/snippets/index.html', { 'snippet_model_opts': sorted( snippet_model_opts, key=lambda x: x.verbose_name.lower())})
def index(request): snippet_model_opts = [ model._meta for model in get_snippet_models() if user_can_edit_snippet_type(request.user, model)] return render(request, 'wagtailsnippets/snippets/index.html', { 'snippet_model_opts': sorted( snippet_model_opts, key=lambda x: x.verbose_name.lower())})
def resolve_models(self): """ Resolve registered Django models omitting pages and snippets. The models need to subclass :class:`wagtail_graphql.models.GraphQLEnabledModel`. """ snippets = get_snippet_models() for model in GraphQLEnabledModel.__subclasses__(): # Do allow Django models only. if not issubclass(model, DjangoModel): raise TypeError('Only Django models are supported') # Do not register pages if issubclass(model, Page): continue # Do not register snippets. if model in snippets: continue # Do not allow registering abstract models. if model._meta.abstract: raise TypeError('Cannot register abstract models') self._models.add(model) self.resolve_model_fields_for(model)
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 user_can_edit_snippets(user): """ true if user has 'add', 'change' or 'delete' permission on any model registered as a snippet type """ snippet_models = get_snippet_models() for model in snippet_models: if user_can_edit_snippet_type(user, model): return True return False
def patch_wagtail_models(): # After all models being registered the Page or BaseSetting subclasses and snippets are patched registered_models = translator.get_registered_models() # We need to sort the models to ensure that subclasses of a model are registered first, # or else if the panels are inherited all the changes on the subclass would be # reflected in the superclass registered_models.sort(key=compare_class_tree_depth) for model_class in registered_models: if issubclass(model_class, Page) or model_class in get_snippet_models() or issubclass(model_class, BaseSetting): WagtailTranslator(model_class)
def _patch_other_models(self, model): if hasattr(model, 'edit_handler'): edit_handler = model.edit_handler for tab in edit_handler: tab.children = self._patch_panels(tab.children) elif hasattr(model, 'panels'): model.panels = self._patch_panels(model.panels) if model in get_snippet_models() and model in SNIPPET_EDIT_HANDLERS: del SNIPPET_EDIT_HANDLERS[model] else: get_setting_edit_handler.cache_clear()
def patch_wagtail_models(): # After all models being registered the Page or BaseSetting subclasses and snippets are patched registered_models = translator.get_registered_models() # We need to sort the models to ensure that subclasses of a model are registered first, # or else if the panels are inherited all the changes on the subclass would be # reflected in the superclass registered_models.sort(key=compare_class_tree_depth) for model_class in registered_models: if issubclass(model_class, Page) or model_class in get_snippet_models() or issubclass(model_class, BaseSetting): WagtailTranslator(model_class)
def user_can_edit_snippets(user): """ true if user has 'add', 'change' or 'delete' permission on any model registered as a snippet type """ snippet_models = get_snippet_models() for model in snippet_models: if user_can_edit_snippet_type(user, model): return True return False
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 add_app(app: str, prefix: str = '{app}') -> None: from django.contrib.contenttypes.models import ContentType from wagtail.snippets.models import get_snippet_models snippets = get_snippet_models() models = [ mdl.model_class() for mdl in ContentType.objects.filter(app_label=app).all() ] to_register = [x for x in snippets + models if x is not None] registered: Set = set() for cls in to_register: _register_model(registered, cls, cls in snippets, app, prefix)
def index(request): snippet_model_opts = [ model._meta for model in get_snippet_models() if user_can_edit_snippet_type(request.user, model) ] if snippet_model_opts: return TemplateResponse( request, 'wagtailsnippets/snippets/index.html', { 'snippet_model_opts': sorted(snippet_model_opts, key=lambda x: x.verbose_name.lower()) }) else: raise PermissionDenied
def get_snippet_model_from_url_params(app_name, model_name): """ Retrieve a model from an app_label / model_name combo. Raise Http404 if the model is not a valid snippet type. """ try: model = apps.get_model(app_name, model_name) except LookupError: raise Http404 if model not in get_snippet_models(): # don't allow people to hack the URL to edit content types that aren't registered as snippets raise Http404 return model
def get_snippet_model_from_url_params(app_name, model_name): """ Retrieve a model from an app_label / model_name combo. Raise Http404 if the model is not a valid snippet type. """ try: model = apps.get_model(app_name, model_name) except LookupError: raise Http404 if model not in get_snippet_models(): # don't allow people to hack the URL to edit content types that aren't registered as snippets raise Http404 return model
class SnippetBulkAction(BulkAction): models = get_snippet_models() def object_context(self, snippet): return { "item": snippet, "edit_url": get_edit_url(self.model._meta.app_label, self.model._meta.model_name, snippet), } def get_context_data(self, **kwargs): kwargs.update({"model_opts": self.model._meta}) return super().get_context_data(**kwargs) def get_execution_context(self): return {**super().get_execution_context(), "self": self}
def register_model(cls: type, type_prefix: str): """ Pass model to the right node type creator based on it's base class. """ # Pass class to correct type creator. if cls is not None: if issubclass(cls, WagtailPage): register_page_model(cls, type_prefix) elif issubclass(cls, AbstractDocument): register_documment_model(cls, type_prefix) elif issubclass(cls, AbstractImage): register_image_model(cls, type_prefix) elif issubclass(cls, BaseSetting): register_settings_model(cls, type_prefix) elif cls in get_snippet_models(): register_snippet_model(cls, type_prefix) else: register_django_model(cls, type_prefix)
def add_app(app_label: str, prefix: str = ""): """ Iterate through each model in the app and pass it to node type creators. """ from django.apps import apps # Get the required django app. app = apps.get_app_config(app_label) # Create a collection of models of standard models (Pages, Images, Documents). models = [mdl for mdl in app.get_models()] # Add snippet models to model collection. for snippet in get_snippet_models(): if snippet._meta.app_label == app_label: models.append(snippet) # Create add each model to correct section of registry. for model in models: register_model(model, prefix)
def add_app(app: str, prefix: str = ""): """ Iterate through each model in the app and pass it to node type creators. """ # Create a collection of models of standard models (Pages, Images, # Documents). models = [ mdl.model_class() for mdl in ContentType.objects.filter(app_label=app).all() ] # Add snippet models to model collection. for snippet in get_snippet_models(): if snippet._meta.app_label == app: models.append(snippet) # Create add each model to correct section of registry. for model in models: register_model(model, prefix)
def choose_snippet_link_model(request): snippet_model_opts = [] # Only display those snippet models which have snippet link frontend template for snippet_model in get_snippet_models(): snippet_frontend_template = get_snippet_link_frontend_template( snippet_model._meta.app_label, snippet_model._meta.model_name) try: get_template(snippet_frontend_template) snippet_model_opts.append(snippet_model._meta) except TemplateDoesNotExist: pass return render_modal_workflow( request, "wagtail_draftail_snippet/choose_snippet_model.html", None, {"snippet_model_opts": snippet_model_opts}, json_data={"step": "choose"}, )
def register_viewsets(): viewsets = [] for model in get_snippet_models(): admin_viewset = ( getattr(model, "admin_viewset", None) or snippet_views.SnippetViewSet ) if isinstance(admin_viewset, str): admin_viewset = import_string(admin_viewset) viewsets += [ admin_viewset( model.get_admin_url_namespace(), model=model, url_prefix=model.get_admin_base_path(), ), chooser_views.SnippetChooserViewSet( f"wagtailsnippetchoosers_{model._meta.app_label}_{model._meta.model_name}", model=model, url_prefix=f"snippets/choose/{model._meta.app_label}/{model._meta.model_name}", ), ] return viewsets
def register_permissions(): content_types = ContentType.objects.get_for_models(*get_snippet_models()).values() return Permission.objects.filter(content_type__in=content_types)
def _get_snippet_types(self): return [ model._meta for model in get_snippet_models() if user_can_edit_snippet_type(self.request.user, model) ]
def autodiscover(): """ Auto-discover INSTALLED_APPS translation.py modules and fail silently when not present. This forces an import on them to register. Also import explicit modules. """ import os import sys import copy from django.conf import settings from django.utils.module_loading import module_has_submodule from wagtail_modeltranslation.translator import translator from wagtail_modeltranslation.settings import TRANSLATION_FILES, DEBUG if django.VERSION < (1, 7): from django.utils.importlib import import_module mods = [(app, import_module(app)) for app in settings.INSTALLED_APPS] else: from importlib import import_module from django.apps import apps mods = [(app_config.name, app_config.module) for app_config in apps.get_app_configs()] for (app, mod) in mods: # Attempt to import the app's translation module. module = '%s.translation' % app before_import_registry = copy.copy(translator._registry) try: import_module(module) except: # Reset the model registry to the state before the last import as # this import will have to reoccur on the next request and this # could raise NotRegistered and AlreadyRegistered exceptions translator._registry = before_import_registry # Decide whether to bubble up this error. If the app just # doesn't have an translation module, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(mod, 'translation'): raise for module in TRANSLATION_FILES: import_module(module) # After all models being registered the Page subclasses and snippets are patched for model in translator.get_registered_models(): if issubclass(model, Page) or model in get_snippet_models(): WagtailTranslator(model) # In debug mode, print a list of registered models and pid to stdout. # Note: Differing model order is fine, we don't rely on a particular # order, as far as base classes are registered before subclasses. if DEBUG: try: if sys.argv[1] in ('runserver', 'runserver_plus'): models = translator.get_registered_models() names = ', '.join(m.__name__ for m in models) print('wagtail_modeltranslation: Registered %d models for ' 'translation (%s) [pid: %d].' % (len(models), names, os.getpid())) except IndexError: pass
def index(request): snippet_model_opts = [ model._meta for model in get_snippet_models() if user_can_edit_snippet_type(request.user, model)] # Return current BatchNum Specs tmp = StaticsDetail.objects.values('BatchNum').distinct() BatchNums = [] for i in range(len(tmp)): BatchNums.append(tmp[i]['BatchNum']) curStatics = StaticsDetail.objects.latest('id') curBatchNum = curStatics.BatchNum defectRate = 0 dic = { "油污": 11.5, "浆斑": 11.5, "停车痕": 11.5, "并纬": 11.5, "擦白": 11.5, "擦伤": 11.5, "错花": 11.5, "断经": 11.5, "断纬": 11.5, "尽机": 11.5, "经条": 11.5, "空织": 11.5, "起机": 11.5, "缺纬": 11.5, "缩纬": 11.5, "折返": 11.5, "其他": 11.5, "糙纬": 11.5, } # filter curStatics = StaticsDetail.objects.all() if (request.POST): batchnum = request.POST['BatchNum'] curStatics = StaticsDetail.objects.get(BatchNum=batchnum) curBatchNum = curStatics.BatchNum if curStatics.DefectCount != 0: dic = { "油污": (curStatics.YW/curStatics.DefectCount*0.885+0.115)*100, "浆斑": (curStatics.JB/curStatics.DefectCount*0.885+0.115)*100, "停车痕": ((curStatics.TCHJ+curStatics.TCHS)/curStatics.DefectCount*0.885+0.115)*100, "并纬": (curStatics.BW/curStatics.DefectCount*0.885+0.115)*100, "擦白": (curStatics.CB/curStatics.DefectCount*0.885+0.115)*100, "擦伤": (curStatics.CS/curStatics.DefectCount*0.885+0.115)*100, "错花": (curStatics.CH/curStatics.DefectCount*0.885+0.115)*100, "断经": ((curStatics.DJ1+curStatics.DJ2)/curStatics.DefectCount*0.885+0.115)*100, "断纬": (curStatics.DW/curStatics.DefectCount*0.885+0.115)*100, "尽机": (curStatics.JJ/curStatics.DefectCount*0.885+0.115)*100, "经条": (curStatics.JT/curStatics.DefectCount*0.885+0.115)*100, "空织": (curStatics.KZ/curStatics.DefectCount*0.885+0.115)*100, "起机": (curStatics.QJ/curStatics.DefectCount*0.885+0.115)*100, "缺纬": ((curStatics.QW1+curStatics.QW2)/curStatics.DefectCount*0.885+0.115)*100, "缩纬": (curStatics.SW/curStatics.DefectCount*0.885+0.115)*100, "折返": (curStatics.ZF/curStatics.DefectCount*0.885+0.115)*100, "其他": (curStatics.QT/curStatics.DefectCount*0.885+0.115)*100, "糙纬": (curStatics.CW/curStatics.DefectCount*0.885+0.115)*100, } defectRate = int(curStatics.DefectCount/curStatics.CountAll*100) orderList = sorted(dic.items(), key=lambda item: item[1], reverse=True) if request.method == 'POST': form = StatisticsForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = StatisticsForm() return render(request, 'wagtailsnippets/snippets/index.html', { 'snippet_model_opts': sorted( snippet_model_opts, key=lambda x: x.verbose_name.lower()), 'BatchNums': BatchNums, 'orderList': orderList, 'defectRate': defectRate, 'curBatchNum': curBatchNum, 'form': form, })
def register_permissions(): content_types = ContentType.objects.get_for_models( *get_snippet_models()).values() return Permission.objects.filter(content_type__in=content_types)
def _get_snippet_types(self): return [{ "model_opts": model._meta, "model": model } for model in get_snippet_models() if user_can_edit_snippet_type(self.request.user, model)]