def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): if not add: if request.method == 'GET' and not obj.is_active: messages.warning(request, 'This account is disabled.') context.update({ 'services': sorted([ model._meta for model in services.get() if model is not Account ], key=lambda i: i.verbose_name_plural.lower()), 'accounts': sorted([ model._meta for model in accounts.get() if model is not Account ], key=lambda i: i.verbose_name_plural.lower()) }) return super(AccountAdmin, self).render_change_form(request, context, add, change, form_url, obj)
def service_report(modeladmin, request, queryset): # TODO resources accounts = [] fields = [] registered_services = services.get() # First we get related manager names to fire a prefetch related for name, field in queryset.model._meta.fields_map.items(): model = field.related_model if model in registered_services and model != queryset.model: fields.append((model, name)) sorted(fields, key=lambda f: f[0]._meta.verbose_name_plural.lower()) fields = [field for model, field in fields] for account in queryset.prefetch_related(*fields): items = [] for field in fields: related_manager = getattr(account, field) items.append((related_manager.model._meta, related_manager.all())) accounts.append((account, items)) context = { 'accounts': accounts, 'date': timezone.now().today() } return render(request, settings.ACCOUNTS_SERVICE_REPORT_TEMPLATE, context)
def get_application_modules(self): modules = super(OrchestraIndexDashboard, self).get_application_modules() models = [] for model, options in services.get().items(): if options.get('menu', True): models.append("%s.%s" % (model.__module__, model._meta.object_name)) for module in modules: registered = self._registry.get(module.title, None) if registered: for view_name, title in registered: # This values are shit, but it is how fluent dashboard will look for the icon app_name, name = view_name.split('_')[:-1] url = reverse('admin:' + view_name) add_url = '/'.join(url.split('/')[:-2]) module.children.append({ 'models': [{ 'add_url': add_url, 'app_name': app_name, 'change_url': url, 'name': name, 'title': title }], 'name': app_name, 'title': title, 'url': add_url, }) service_icon_list = CmsAppIconList('Services', models=models, collapsible=True) modules.append(service_icon_list) return modules
def formfield_for_dbfield(self, db_field, **kwargs): """ filter service content_types """ if db_field.name == 'content_type': models = [model._meta.model_name for model in services.get()] kwargs['queryset'] = db_field.remote_field.model.objects.filter( model__in=models) return super(ResourceAdmin, self).formfield_for_dbfield(db_field, **kwargs)
def formfield_for_dbfield(self, db_field, **kwargs): """ Improve performance of account field and filter by account """ if db_field.name == "content_type": models = [model._meta.model_name for model in services.get()] queryset = db_field.rel.to.objects kwargs["queryset"] = queryset.filter(model__in=models) if db_field.name in ["match", "metric", "order_description"]: kwargs["widget"] = forms.TextInput(attrs={"size": "160"}) return super(ServiceAdmin, self).formfield_for_dbfield(db_field, **kwargs)
def formfield_for_dbfield(self, db_field, **kwargs): """ Improve performance of account field and filter by account """ if db_field.name == 'content_type': models = [model._meta.model_name for model in services.get()] queryset = db_field.rel.to.objects kwargs['queryset'] = queryset.filter(model__in=models) if db_field.name in ['match', 'metric', 'order_description']: kwargs['widget'] = forms.TextInput(attrs={'size':'160'}) return super(ServiceAdmin, self).formfield_for_dbfield(db_field, **kwargs)
def get_services(): childrens = [] for model, options in services.get().iteritems(): if options.get('menu', True): opts = model._meta url = reverse('admin:{}_{}_changelist'.format( opts.app_label, opts.model_name)) name = capfirst(options.get('verbose_name_plural')) childrens.append(items.MenuItem(name, url)) return sorted(childrens, key=lambda i: i.title)
def formfield_for_dbfield(self, db_field, **kwargs): """ Improve performance of account field and filter by account """ if db_field.name == 'content_type': models = [model._meta.model_name for model in services.get()] queryset = db_field.rel.to.objects kwargs['queryset'] = queryset.filter(model__in=models) if db_field.name in ['match', 'metric', 'order_description']: kwargs['widget'] = forms.TextInput(attrs={'size': '160'}) return super(ServiceAdmin, self).formfield_for_dbfield(db_field, **kwargs)
def generate_services_group(): models = [] for model, options in services.get().iteritems(): if options.get('menu', True): models.append("%s.%s" % (model.__module__, model._meta.object_name)) settings.FLUENT_DASHBOARD_APP_GROUPS += ( ('Services', { 'models': models, 'collapsible': True }), )
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): if not add: if request.method == 'GET' and not obj.is_active: messages.warning(request, 'This account is disabled.') context.update({ 'services': sorted( [model._meta for model in services.get() if model is not Account], key=lambda i: i.verbose_name_plural.lower() ), 'accounts': sorted( [model._meta for model in accounts.get() if model is not Account], key=lambda i: i.verbose_name_plural.lower() ) }) return super(AccountAdmin, self).render_change_form( request, context, add, change, form_url, obj)
def change_view(self, request, object_id, form_url='', extra_context=None): if request.method == 'GET': account = self.get_object(request, unquote(object_id)) if not account.is_active: messages.warning(request, 'This account is disabled.') context = { 'services': sorted( [model._meta for model in services.get() if model is not Account], key=lambda i: i.verbose_name_plural.lower() ), 'accounts': sorted( [model._meta for model in accounts.get() if model is not Account], key=lambda i: i.verbose_name_plural.lower() ) } context.update(extra_context or {}) return super(AccountAdmin, self).change_view(request, object_id, form_url=form_url, extra_context=context)
def service_report(modeladmin, request, queryset): # TODO resources accounts = [] fields = [] registered_services = services.get() # First we get related manager names to fire a prefetch related for name, field in queryset.model._meta.fields_map.items(): model = field.related_model if model in registered_services and model != queryset.model: fields.append((model, name)) fields = sorted(fields, key=lambda f: f[0]._meta.verbose_name_plural.lower()) fields = [field for model, field in fields] for account in queryset.prefetch_related(*fields): items = [] for field in fields: related_manager = getattr(account, field) items.append((related_manager.model._meta, related_manager.all())) accounts.append((account, items)) context = {'accounts': accounts, 'date': timezone.now().today()} return render(request, settings.ACCOUNTS_SERVICE_REPORT_TEMPLATE, context)
def formfield_for_dbfield(self, db_field, **kwargs): """ filter service content_types """ if db_field.name == 'content_type': models = [ model._meta.model_name for model in services.get() ] kwargs['queryset'] = db_field.rel.to.objects.filter(model__in=models) return super(ResourceAdmin, self).formfield_for_dbfield(db_field, **kwargs)
def delete_related_services(modeladmin, request, queryset): opts = modeladmin.model._meta app_label = opts.app_label using = router.db_for_write(modeladmin.model) collector = NestedObjects(using=using) collector.collect(queryset) registered_services = services.get() related_services = [] to_delete = [] admin_site = modeladmin.admin_site def format(obj, account=False): has_admin = obj.__class__ in admin_site._registry opts = obj._meta no_edit_link = '%s: %s' % (capfirst( opts.verbose_name), force_text(obj)) if has_admin: try: admin_url = reverse( 'admin:%s_%s_change' % (opts.app_label, opts.model_name), None, (quote(obj._get_pk_val()), )) except NoReverseMatch: # Change url doesn't exist -- don't display link to edit return no_edit_link # Display a link to the admin page. context = (capfirst(opts.verbose_name), admin_url, obj) if account: context += (_("services to delete:"), ) return format_html('{} <a href="{}">{}</a> {}', *context) return format_html('{}: <a href="{}">{}</a>', *context) else: # Don't display link to edit, because it either has no # admin or is edited inline. return no_edit_link def format_nested(objs, result): if isinstance(objs, list): current = [] for obj in objs: format_nested(obj, current) result.append(current) else: result.append(format(objs)) for nested in collector.nested(): if isinstance(nested, list): # Is lists of objects current = [] is_service = False for service in nested: if type(service) in registered_services: if service == main_systemuser: continue current.append(format(service)) to_delete.append(service) is_service = True elif is_service and isinstance(service, list): nested = [] format_nested(service, nested) current.append(nested[0]) is_service = False else: is_service = False related_services.append(current) elif isinstance(nested, modeladmin.model): # Is account # Prevent the deletion of the main system user, which will delete the account main_systemuser = nested.main_systemuser related_services.append(format(nested, account=True)) # The user has already confirmed the deletion. # Do the deletion and return a None to display the change list view again. if request.POST.get('post'): accounts = len(queryset) msg = _("Related services deleted and account disabled.") for account in queryset: account.is_active = False account.save(update_fields=('is_active', )) modeladmin.log_change(request, account, msg) if accounts: relateds = len(to_delete) for obj in to_delete: obj_display = force_text(obj) modeladmin.log_deletion(request, obj, obj_display) obj.delete() context = { 'accounts': accounts, 'relateds': relateds, } msg = _( "Successfully disabled %(accounts)d account and deleted %(relateds)d related services." ) % context modeladmin.message_user(request, msg, messages.SUCCESS) # Return None to display the change list page again. return None if len(queryset) == 1: objects_name = force_text(opts.verbose_name) else: objects_name = force_text(opts.verbose_name_plural) model_count = {} for model, objs in collector.model_objs.items(): count = 0 # discount main systemuser if model is modeladmin.model.main_systemuser.field.rel.to: count = len(objs) - 1 # Discount account elif model is not modeladmin.model and model in registered_services: count = len(objs) if count: model_count[model._meta.verbose_name_plural] = count if not model_count: modeladmin.message_user(request, _("Nothing to delete"), messages.WARNING) return None context = dict( admin_site.each_context(request), title=_("Are you sure?"), objects_name=objects_name, deletable_objects=[related_services], model_count=dict(model_count).items(), queryset=queryset, opts=opts, action_checkbox_name=helpers.ACTION_CHECKBOX_NAME, ) request.current_app = admin_site.name # Display the confirmation page template = 'admin/%s/%s/delete_related_services_confirmation.html' % ( app_label, opts.model_name) return TemplateResponse(request, template, context)
def delete_related_services(modeladmin, request, queryset): opts = modeladmin.model._meta app_label = opts.app_label using = router.db_for_write(modeladmin.model) collector = NestedObjects(using=using) collector.collect(queryset) registered_services = services.get() related_services = [] to_delete = [] user = request.user admin_site = modeladmin.admin_site def format(obj, account=False): has_admin = obj.__class__ in admin_site._registry opts = obj._meta no_edit_link = '%s: %s' % (capfirst(opts.verbose_name), force_text(obj)) if has_admin: try: admin_url = reverse('admin:%s_%s_change' % (opts.app_label, opts.model_name), None, (quote(obj._get_pk_val()),) ) except NoReverseMatch: # Change url doesn't exist -- don't display link to edit return no_edit_link p = '%s.%s' % (opts.app_label, get_permission_codename('delete', opts)) if not user.has_perm(p): perms_needed.add(opts.verbose_name) # Display a link to the admin page. context = (capfirst(opts.verbose_name), admin_url, obj) if account: context += (_("services to delete:"),) return format_html('{} <a href="{}">{}</a> {}', *context) return format_html('{}: <a href="{}">{}</a>', *context) else: # Don't display link to edit, because it either has no # admin or is edited inline. return no_edit_link def format_nested(objs, result): if isinstance(objs, list): current = [] for obj in objs: format_nested(obj, current) result.append(current) else: result.append(format(objs)) for nested in collector.nested(): if isinstance(nested, list): # Is lists of objects current = [] is_service = False for service in nested: if type(service) in registered_services: if service == main_systemuser: continue current.append(format(service)) to_delete.append(service) is_service = True elif is_service and isinstance(service, list): nested = [] format_nested(service, nested) current.append(nested) is_service = False else: is_service = False related_services.append(current) elif isinstance(nested, modeladmin.model): # Is account # Prevent the deletion of the main system user, which will delete the account main_systemuser = nested.main_systemuser related_services.append(format(nested, account=True)) # The user has already confirmed the deletion. # Do the deletion and return a None to display the change list view again. if request.POST.get('post'): n = queryset.count() if n: for obj in to_delete: obj_display = force_text(obj) modeladmin.log_deletion(request, obj, obj_display) # TODO This probably will fail in certain conditions, just capture exception obj.delete() modeladmin.message_user(request, _("Successfully deleted %(count)d %(items)s.") % { "count": n, "items": model_ngettext(modeladmin.opts, n) }, messages.SUCCESS) # Return None to display the change list page again. return None if len(queryset) == 1: objects_name = force_text(opts.verbose_name) else: objects_name = force_text(opts.verbose_name_plural) context = dict( modeladmin.admin_site.each_context(request), title=_("Are you sure?"), objects_name=objects_name, deletable_objects=[related_services], model_count=dict(collector.model_count).items(), queryset=queryset, opts=opts, action_checkbox_name=helpers.ACTION_CHECKBOX_NAME, ) request.current_app = modeladmin.admin_site.name # Display the confirmation page return TemplateResponse(request, modeladmin.delete_selected_confirmation_template or [ "admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.model_name), "admin/%s/delete_selected_confirmation.html" % app_label, "admin/delete_selected_confirmation.html" ], context)
def delete_related_services(modeladmin, request, queryset): opts = modeladmin.model._meta app_label = opts.app_label using = router.db_for_write(modeladmin.model) collector = NestedObjects(using=using) collector.collect(queryset) registered_services = services.get() related_services = [] to_delete = [] admin_site = modeladmin.admin_site def format(obj, account=False): has_admin = obj.__class__ in admin_site._registry opts = obj._meta no_edit_link = '%s: %s' % (capfirst(opts.verbose_name), force_text(obj)) if has_admin: try: admin_url = reverse( 'admin:%s_%s_change' % (opts.app_label, opts.model_name), None, (quote(obj._get_pk_val()),) ) except NoReverseMatch: # Change url doesn't exist -- don't display link to edit return no_edit_link # Display a link to the admin page. context = (capfirst(opts.verbose_name), admin_url, obj) if account: context += (_("services to delete:"),) return format_html('{} <a href="{}">{}</a> {}', *context) return format_html('{}: <a href="{}">{}</a>', *context) else: # Don't display link to edit, because it either has no # admin or is edited inline. return no_edit_link def format_nested(objs, result): if isinstance(objs, list): current = [] for obj in objs: format_nested(obj, current) result.append(current) else: result.append(format(objs)) for nested in collector.nested(): if isinstance(nested, list): # Is lists of objects current = [] is_service = False for service in nested: if type(service) in registered_services: if service == main_systemuser: continue current.append(format(service)) to_delete.append(service) is_service = True elif is_service and isinstance(service, list): nested = [] format_nested(service, nested) current.append(nested) is_service = False else: is_service = False related_services.append(current) elif isinstance(nested, modeladmin.model): # Is account # Prevent the deletion of the main system user, which will delete the account main_systemuser = nested.main_systemuser related_services.append(format(nested, account=True)) # The user has already confirmed the deletion. # Do the deletion and return a None to display the change list view again. if request.POST.get('post'): accounts = len(queryset) msg = _("Related services deleted and account disabled.") for account in queryset: account.is_active = False account.save(update_fields=('is_active',)) modeladmin.log_change(request, account, msg) if accounts: relateds = len(to_delete) for obj in to_delete: obj_display = force_text(obj) modeladmin.log_deletion(request, obj, obj_display) obj.delete() context = { 'accounts': accounts, 'relateds': relateds, } msg = _("Successfully disabled %(accounts)d account and deleted %(relateds)d related services.") % context modeladmin.message_user(request, msg, messages.SUCCESS) # Return None to display the change list page again. return None if len(queryset) == 1: objects_name = force_text(opts.verbose_name) else: objects_name = force_text(opts.verbose_name_plural) context = dict( admin_site.each_context(request), title=_("Are you sure?"), objects_name=objects_name, deletable_objects=[related_services], model_count=dict(collector.model_count).items(), queryset=queryset, opts=opts, action_checkbox_name=helpers.ACTION_CHECKBOX_NAME, ) request.current_app = admin_site.name # Display the confirmation page template = 'admin/%s/%s/delete_related_services_confirmation.html' % (app_label, opts.model_name) return TemplateResponse(request, template, context)