我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用django.contrib.admin()。
def get_urlpatterns(handler_module): # NB: This could just as well be your `urls.py` – it's here to make testing various handler # configurations easier. router = Router.from_file(os.path.join(os.path.dirname(__file__), 'tests', 'petstore-expanded.yaml')) router.add_handlers(handler_module) validate_router(router) router_urls = router.get_urls( decorate=(csrf_exempt,), optional_trailing_slash=True, ) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include(router_urls, 'api')), url(r'^api/', include(get_docs_urls(router, 'api-docs'), 'api-docs')), ] return urlpatterns
def test_check_get_requests_allowed(self): self.assertTrue(hijack_settings.HIJACK_ALLOW_GET_REQUESTS) errors = checks.check_get_requests_allowed(HijackAdminConfig) self.assertFalse(errors) with SettingsOverride(hijack_settings, HIJACK_ALLOW_GET_REQUESTS=False): errors = checks.check_get_requests_allowed(HijackAdminConfig) expected_errors = [ Error( 'Hijack GET requests must be allowed for django-hijack-admin to work.', hint='Set HIJACK_ALLOW_GET_REQUESTS to True.', obj=None, id='hijack_admin.E001', ) ] self.assertEqual(errors, expected_errors)
def display_users(self, obj): links = [] for user in obj.user_set.all(): ct = ContentType.objects.get_for_model(user) url = reverse( "admin:{}_{}_change".format( ct.app_label, ct.model ), args=(user.id,) ) links.append( """<a href="{}" target="_blank">{}</a>""".format( url, "{} {}".format( user.first_name, user.last_name ).strip() or user.username, ) ) return u"<br />".join(links)
def _remove_app_models(all_apps, models_to_remove): """ Remove the model specs in models_to_remove from the models specs in the apps in all_apps. If an app has no models left, don't include it in the output. This has the side-effect that the app view e.g. /admin/app/ may not be accessible from the dashboard, only the breadcrumbs. """ filtered_apps = [] for app in all_apps: models = [x for x in app['models'] if x not in models_to_remove] if models: app['models'] = models filtered_apps.append(app) return filtered_apps
def safe_unregister(self, *args, **kwargs): """ Checks the deferred unregister for an existing unregister and doesn't add another one for this model returns False if this unregister call was skipped returns True if this unregister call was added This is mostly for re-registering Page models to the Clubhouse.admin.PageAdmin class.. """ # TODO: Possibly a smarter unregister / register check # this method assumes that if the admin has been unregistered # and needs to be re-registered you will use the clubhouse.PageAdmin # class. for name, deferred_args, deferred_kwargs in self._deferred: if name == "unregister" and deferred_args[0] == args[0]: return False else: self.unregister(*args, **kwargs) return True
def tb_check(request): objlist = func.get_mysql_hostlist(request.user.username, 'meta') if request.method == 'POST': choosed_host = request.POST['choosed'] if request.POST.has_key('bigtb'): data_list,collist = meta.get_his_meta(choosed_host,1) elif request.POST.has_key('auto_occ'): data_list, collist = meta.get_his_meta(choosed_host,2) elif request.POST.has_key('tb_incre'): data_list, collist = meta.get_his_meta(choosed_host,3) elif request.POST.has_key('db_sz'): data_list, collist = meta.get_his_meta(choosed_host, 4) elif request.POST.has_key('db_inc'): data_list, collist = meta.get_his_meta(choosed_host, 5) return render(request, 'admin/tb_check.html', locals()) else: return render(request, 'admin/tb_check.html', locals())
def test_edit_title_dirty_bit(self): language = "en" admin_user = self.get_admin() page = create_page('A', 'nav_playground.html', language) page_admin = PageAdmin(Page, None) page_admin._current_page = page page.publish("en") draft_page = page.get_draft_object() admin_url = reverse("admin:cms_page_edit_title_fields", args=( draft_page.pk, language )) post_data = { 'title': "A Title" } with self.login_user_context(admin_user): self.client.post(admin_url, post_data) draft_page = Page.objects.get(pk=page.pk).get_draft_object() self.assertTrue(draft_page.is_dirty('en'))
def test_edit_title_languages(self): language = "en" admin_user = self.get_admin() page = create_page('A', 'nav_playground.html', language) page_admin = PageAdmin(Page, None) page_admin._current_page = page page.publish("en") draft_page = page.get_draft_object() admin_url = reverse("admin:cms_page_edit_title_fields", args=( draft_page.pk, language )) post_data = { 'title': "A Title" } with self.login_user_context(admin_user): self.client.post(admin_url, post_data) draft_page = Page.objects.get(pk=page.pk).get_draft_object() self.assertTrue(draft_page.is_dirty('en'))
def test_plugin_add_returns_valid_pk_for_plugin(self): admin_user = self._get_admin() self._give_cms_permissions(admin_user) self._give_permission(admin_user, Text, 'add') username = getattr(admin_user, get_user_model().USERNAME_FIELD) self.client.login(username=username, password='admin') url = admin_reverse('cms_page_add_plugin') data = { 'plugin_type': 'TextPlugin', 'placeholder_id': self._placeholder.pk, 'plugin_language': 'en', 'plugin_parent': '', } response = self.client.post(url, data) self.assertEqual(response.status_code, HttpResponse.status_code) self.assertEqual(response['content-type'], 'application/json') pk = response.content.decode('utf8').split("edit-plugin/")[1].split("/")[0] self.assertTrue(CMSPlugin.objects.filter(pk=int(pk)).exists())
def get_revision_instances(self, request, object): """Returns all the instances to be used in the object's revision.""" if isinstance(object, Title): object = object.page if isinstance(object, Page) and not object.publisher_is_draft: object = object.publisher_public placeholder_relation = find_placeholder_relation(object) data = [object] filters = {'placeholder__%s' % placeholder_relation: object} for plugin in CMSPlugin.objects.filter(**filters): data.append(plugin) plugin_instance, admin = plugin.get_plugin_instance() if plugin_instance: data.append(plugin_instance) if isinstance(object, Page): titles = object.title_set.all() for title in titles: title.publisher_public = None data.append(title) return data
def response_post_save_change(self, request, obj): # # When the user changes his language setting, we need to do two things: # 1. Change the language-prefix for the sideframed admin view # 2. Reload the whole window so that the new language affects the # toolbar, etc. # # To do this, we first redirect the sideframe to the correct new, URL, # but we pass a GET param 'reload_window', which instructs JS on that # page to strip (to avoid infinite redirection loops) that param then # reload the whole window again. # with override(obj.language): post_url = admin_reverse( 'cms_usersettings_change', args=[obj.id, ], current_app=self.admin_site.name ) return HttpResponseRedirect("{0}?reload_window".format(post_url))
def setUp(self): self.user = G(User) self.admin = G( User, is_staff=True, is_active=True, is_superuser=True, ) self.layout = G( PageLayout, template_path='default.html', ) self.page = Page.objects.create( author=self.admin, title='Hello, world!', slug='hello-world', layout=self.layout, ) self.content_instance = create_content_instance( RawHtmlItem, self.page, placeholder_name='content', html='<b>lorem ipsum dolor sit amet...</b>' )
def _build_context(self, request, customer_uuid): """ Build common context parts used by different handlers in this view. """ # TODO: pylint acts stupid - find a way around it without suppressing enterprise_customer = EnterpriseCustomer.objects.get(uuid=customer_uuid) # pylint: disable=no-member search_keyword = self.get_search_keyword(request) linked_learners = self.get_enterprise_customer_user_queryset(search_keyword, customer_uuid) pending_linked_learners = self.get_pending_users_queryset(search_keyword, customer_uuid) context = { self.ContextParameters.ENTERPRISE_CUSTOMER: enterprise_customer, self.ContextParameters.PENDING_LEARNERS: pending_linked_learners, self.ContextParameters.LEARNERS: linked_learners, self.ContextParameters.SEARCH_KEYWORD: search_keyword or '', self.ContextParameters.ENROLLMENT_URL: settings.LMS_ENROLLMENT_API_PATH, } context.update(admin.site.each_context(request)) context.update(self._build_admin_context(request, enterprise_customer)) return context
def test_admin_template_renders_switcher(self): user = User.objects.create_user( username='admin', password='password' ) user.is_staff = True user.save() self.client.login(username='admin', password='password') Schema.objects.mass_create('a', 'b') a = Schema.objects.get(pk='a') user.schemata.add(a) a.activate() user.user_permissions.add(Permission.objects.get(codename='change_awaremodel')) self.client.get('/?__schema=a') response = self.client.get(reverse('admin:tests_awaremodel_changelist')) self.assertTemplateUsed(response, 'boardinghouse/change_schema.html')
def revert(self, request, queryset): """ Admin action to revert a configuration back to the selected value """ if queryset.count() != 1: self.message_user(request, _("Please select a single configuration to revert to.")) return target = queryset[0] target.id = None target.changed_by = request.user target.save(action_type='create') self.message_user(request, _("Reverted configuration.")) return HttpResponseRedirect( reverse( 'admin:{}_{}_change'.format( self.model._meta.app_label, self.model._meta.model_name, ), args=(target.id,), ) )
def get_inline_actions(self, request, obj=None): """ Returns a list of all actions for this Admin. """ # If self.actions is explicitly set to None that means that we don't # want *any* actions enabled on this page. if self.inline_actions is None: return [] actions = [] # Gather actions from the inline admin and all parent classes, # starting with self and working back up. for klass in self.__class__.mro()[::-1]: class_actions = getattr(klass, 'inline_actions', []) # Avoid trying to iterate over None if not class_actions: continue for action in class_actions: if action not in actions: actions.append(action) return actions
def dispatch(self, request, *args, **kwargs): if not utils.docutils_is_available: # Display an error message for people without docutils self.template_name = 'admin_doc/missing_docutils.html' return self.render_to_response(admin.site.each_context(request)) return super(BaseAdminDocsView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs): kwargs.update({'root_path': urlresolvers.reverse('admin:index')}) kwargs.update(admin.site.each_context(self.request)) return super(BaseAdminDocsView, self).get_context_data(**kwargs)
def get_context_data(self, **kwargs): kwargs.update({'root_path': reverse('admin:index')}) kwargs.update(admin.site.each_context(self.request)) return super(BaseAdminDocsView, self).get_context_data(**kwargs)
def _get_media(): js = [ 'calendar.js', 'admin/DateTimeShortcuts.js', ] css = [ 'widgets.css', ] return forms.Media( js=['admin/js/%s' % url for url in js], css={'all': ['admin/css/%s' % path for path in css]} )
def post(self, request, *args, **kwargs): """ Custom post method Either exports a CSV or displays a form with errors :param request: Http Request instance :type request: django.http.HttpRequest :param args: Default positional args :type args: () :param kwargs: Default keyword args :type kwargs: {} :return: Http Response instance """ queryset = kwargs.get('queryset') generators = kwargs.get('generators') if generators.count() == 1: return self.render_csv_to_response(generators[0], queryset) form = self.form_class(generators=generators) if 'post' in request.POST: form = self.form_class(data=request.POST, generators=generators) if form.is_valid(): generator = form.cleaned_data.get('generator') return self.render_csv_to_response(generator, queryset) return self.render_to_response({ 'title': 'Export to CSV', 'form': form, 'opts': queryset.model._meta, 'queryset': queryset, 'action_checkbox_name': admin.helpers.ACTION_CHECKBOX_NAME })
def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'title': kwargs['widget'] = AdminTextInputWidget return super(FluentCommentsAdmin, self).formfield_for_dbfield(db_field, **kwargs) # Replace the old admin screen.
def statistics_view(request): """ :param request: Django Request :return: Django HttpResponse :rtype: HttpResponse """ if request.method == 'GET': context = admin.site.each_context(request) context.update({ 'title': _('Statistics'), 'db_status': db_status(), 'stat': statistics(), 'settings': preferences.Setting }) template = 'admin/help/statistics.html' return render(request, template, context) else: if 'action' in request.POST and request.POST['action'] == 'clean': result_dict = {} try: if os.path.exists(TEMP_ROOT): shutil.rmtree(TEMP_ROOT) os.mkdir(TEMP_ROOT) else: os.mkdir(TEMP_ROOT) result_dict = {'status': True} return HttpResponse(json.dumps(result_dict), content_type='application/json') except Exception as e: # error handler result_dict.update({ "success": False, "exception": unicode(e) }) return HttpResponse(json.dumps(result_dict), content_type='application/json')
def about_view(request): """ :param request: Django Request :return: Django HttpResponse :rtype: HttpResponse """ context = admin.site.each_context(request) context.update({ 'title': _('About'), 'version': "4.0 Build 4096", }) template = 'admin/help/about.html' return render(request, template, context)
def test_check_custom_user_model(self): # Django doesn't re-register admins when using `override_settings`, # so we have to do it manually in this test case. admin.site.register(get_user_model(), HijackUserAdmin) warnings = checks.check_custom_user_model(HijackAdminConfig) self.assertFalse(warnings) admin.site.unregister(get_user_model())
def test_check_custom_user_model_default_admin(self): # Django doesn't re-register admins when using `override_settings`, # so we have to do it manually in this test case. admin.site.register(get_user_model(), UserAdmin) warnings = checks.check_custom_user_model(HijackAdminConfig) expected_warnings = [ Warning( 'django-hijack-admin does not work out the box with a custom user model.', hint='Please mix HijackUserAdminMixin into your custom UserAdmin.', obj=settings.AUTH_USER_MODEL, id='hijack_admin.W001', ) ] self.assertEqual(warnings, expected_warnings) admin.site.unregister(get_user_model())
def clear_logs(request): """Clear admin activity logs if user has permissions""" if not request.user.is_authenticated(): # should be applied to anything under /console return redirect('login') if request.user.has_perm('admin.delete_logentry'): LogEntry.objects.all().filter(user__pk=request.user.id).delete() messages.info(request, 'Successfully cleared admin activity logs.', fail_silently=True) else: messages.warning(request, 'Unable to clear the admin activity logs.', fail_silently=True) return redirect('admin:index')
def _print_link_to_account(self, account, label_lambda): return '<a href="{url}">{label}</a>'.format( url=reverse('admin:%s_%s_change' % (account._meta.app_label, account._meta.model_name), args=(account.id,)), label=(label_lambda(account) + (" (connected)" if account.connected else "")) )
def print_link_to_profile(self, profile): return '<a href="{url}">{label}</a>'.format( url=reverse('admin:%s_%s_change' % (profile._meta.app_label, profile._meta.model_name), args=(profile.id,)), label=str(profile) )
def openwisp_admin(site_url=None): # <title> admin.site.site_title = ugettext_lazy('OpenWISP2 Admin') # link to frontend admin.site.site_url = site_url # h1 text admin.site.site_header = ugettext_lazy('OpenWISP') # text at the top of the admin index page admin.site.index_title = ugettext_lazy('Network administration')
def object_repr_link(self, obj): if obj.event_type == CRUDEvent.DELETE: html = obj.object_repr else: try: url = urlresolvers.reverse("admin:%s_%s_change" % ( obj.content_type.app_label, obj.content_type.model, ), args=(obj.object_id,)) html = '<a href="%s">%s</a>' % (url, obj.object_repr) except: html = obj.object_repr return mark_safe(html)