我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用django.contrib.admin.site()。
def test_changelist_view(self): request = RequestFactory().get('/') request.user = User.objects.create(username='name', password='pass', is_superuser=True) admin_obj = PreferencesAdmin(MyPreferences, admin.site) # With only one preferences object redirect to its change view. response = admin_obj.changelist_view(request) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/admin/tests/mypreferences/1/change/') # With multiple preferences display listing view. MyPreferences.objects.create() response = admin_obj.changelist_view(request) response.render() self.failUnless('changelist-form' in response.content, 'Should \ display listing if multiple preferences objects are available.')
def index(self, request, *args, **kwargs): extra_context = {} errors = validate_server_db1() errors += validate_server_db2() errors += validate_server_db3() errors += validate_project_db1() errors += validate_project_db2() errors += validate_uwsgi() errors += validate_server_ip() errors += validate_project_dirs() if errors: for e in errors: messages.warning(request, e) return admin.site.__class__.index( self, request, extra_context=extra_context, *args, **kwargs)
def get_admin_site(current_app): """ Method tries to get actual admin.site class, if any custom admin sites were used. Couldn't find any other references to actual class other than in func_closer dict in index() func returned by resolver. """ try: resolver_match = resolve(reverse('%s:index' % current_app)) # Django 1.9 exposes AdminSite instance directly on view function if hasattr(resolver_match.func, 'admin_site'): return resolver_match.func.admin_site for func_closure in resolver_match.func.__closure__: if isinstance(func_closure.cell_contents, AdminSite): return func_closure.cell_contents except: pass return admin.site
def test_datefilter_filtered(self): self.request_factory = RequestFactory() modeladmin = MyModelAdmin(MyModel, site) request = self.request_factory.get('/', {'created_at__gte': self.today, 'created_at__lte': self.tomorrow}) changelist = self.get_changelist(request, MyModel, modeladmin) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.django_book]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_text(filterspec.title), 'created at') choice = select_by(filterspec.choices(changelist)) self.assertEqual(choice['query_string'], '?') self.assertEqual(choice['system_name'], 'created-at')
def test_datefilter_filtered_with_one_params(self): self.request_factory = RequestFactory() modeladmin = MyModelAdmin(MyModel, site) request = self.request_factory.get('/', {'created_at__gte': self.today}) changelist = self.get_changelist(request, MyModel, modeladmin) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.django_book]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_text(filterspec.title), 'created at') choice = select_by(filterspec.choices(changelist)) self.assertEqual(choice['query_string'], '?') self.assertEqual(choice['system_name'], 'created-at')
def test_datefilter_filtered_datefield(self): self.request_factory = RequestFactory() modeladmin = MyModelDateAdmin(MyModelDate, site) request = self.request_factory.get('/', {'created_at__gte': self.today, 'created_at__lte': self.tomorrow}) changelist = self.get_changelist(request, MyModelDate, modeladmin) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.django_book_date]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_text(filterspec.title), 'created at') choice = select_by(filterspec.choices(changelist)) self.assertEqual(choice['query_string'], '?') self.assertEqual(choice['system_name'], 'created-at')
def test_datefilter_filtered_with_one_params(self): self.request_factory = RequestFactory() modeladmin = MyModelTimeAdmin(MyModel, site) request = self.request_factory.get('/', {'created_at__gte_0': self.today, 'created_at__gte_1': self.min_time}) changelist = self.get_changelist(request, MyModel, modeladmin) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.django_book]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_text(filterspec.title), 'created at') choice = select_by(filterspec.choices(changelist)) self.assertEqual(choice['query_string'], '?') self.assertEqual(choice['system_name'], 'created-at')
def test_get_queryset(self): # Should return preferences without sites. # Shouldn't fail on duplicates. self.failIf(MyPreferences.singleton.get().sites.all(), "Without \ SITE_ID should not have any preferences with sites.") # Should return preferences for current site. # Shouldn't fail on duplicates. settings.SITE_ID = 1 current_site = Site.objects.get_current() obj = MyPreferences.singleton.get() self.failUnlessEqual(current_site, obj.sites.get(), "With SITE_ID \ should have preferences for current site.") # Should return preferences for current site. # Shouldn't fail on duplicates. settings.SITE_ID = 2 second_site, created = Site.objects.get_or_create(id=2) obj = MyPreferences.singleton.get() self.failUnlessEqual(second_site, obj.sites.get(), "With SITE_ID \ should have preferences for current site.")
def get_admin_site(current_app): """ Method tries to get actual admin.site class, if any custom admin sites were used. Couldn't find any other references to actual class other than in func_closer dict in index() func returned by resolver. """ try: resolver_match = resolve(reverse('%s:index' % current_app)) # Django 1.9 exposes AdminSite instance directly on view function if hasattr(resolver_match.func, 'admin_site'): return resolver_match.func.admin_site for func_closure in resolver_match.func.__closure__: if isinstance(func_closure.cell_contents, AdminSite): return func_closure.cell_contents except: pass from django.contrib import admin return admin.site
def test_slug_collisions_api_3(self): """ Checks for slug collisions on children of a non root page - uses API to create pages """ page1 = create_page('test page 1', 'nav_playground.html', 'en', published=True) page1_1 = create_page('test page 1_1', 'nav_playground.html', 'en', published=True, parent=page1, slug="foo") page1_1_1 = create_page('test page 1_1_1', 'nav_playground.html', 'en', published=True, parent=page1_1, slug="bar") page1_1_2 = create_page('test page 1_1_1', 'nav_playground.html', 'en', published=True, parent=page1_1, slug="bar") page1_2 = create_page('test page 1_2', 'nav_playground.html', 'en', published=True, parent=page1, slug="bar") # Direct children of home has different slug so it's ok. self.assertTrue(is_valid_page_slug(page1_1, page1_1.parent, "en", page1_1.get_slug("en"), page1_1.site)) self.assertTrue(is_valid_page_slug(page1_2, page1_2.parent, "en", page1_2.get_slug("en"), page1_2.site)) # children of page1_1 has the same slug -> you lose! self.assertFalse( is_valid_page_slug(page1_1_1, page1_1_1.parent, "en", page1_1_1.get_slug("en"), page1_1_1.site)) self.assertFalse( is_valid_page_slug(page1_1_2, page1_1_2.parent, "en", page1_1_2.get_slug("en"), page1_1_2.site))
def test_copy_page_method(self): """ Test that a page can be copied via the admin """ page_a = create_page("page_a", "nav_playground.html", "en", published=False) page_a_a = create_page("page_a_a", "nav_playground.html", "en", parent=page_a, published=False, reverse_id="hello") create_page("page_a_a_a", "nav_playground.html", "en", parent=page_a_a, published=False) site = Site.objects.create(domain='whatever.com', name='whatever') pages = Page.objects.drafts().filter(site_id=1, depth=1) with transaction.atomic(): for page in pages: page.copy_page(None, site) with transaction.atomic(): for page in pages: page.copy_page(None, site) self.assertEqual(Page.objects.filter(site_id=1, depth=1).count(), 1) self.assertEqual(Page.objects.filter(site_id=1).count(), 3) self.assertEqual(Page.objects.filter(site_id=site.pk, depth=1).count(), 2) self.assertEqual(Page.objects.filter(site_id=site.pk).count(), 6)
def test_post_change_form_view__normal_case__correct_template_response(self, _, __): post_data = POST_DETAIL_RESPONSE['response'] post_object = post_factory(post_data) change_url = reverse('{admin_site_name}:{app_label}_{model_name}_change'.format( admin_site_name=admin.site.name, app_label=Post._meta.app_label, model_name=Post._meta.model_name ), args=[post_object.id]) request = RequestFactory().get(change_url, follow=True) request.user = MockSuperUser() response = PostAdmin(Post, admin.site).change_view(request, post_data['id']) template_names = set([ 'admin/change_form.html', 'admin/disqus_backstore/change_form.html', 'admin/disqus_backstore/post/change_form.html', ]) self.assertEqual(response.status_code, 200) self.assertEqual(set(response.template_name), template_names) self.assertEqual( response.context_data['adminform'].form['id'].value(), post_object.id )
def make_site(): admin.autodiscover() # now kill off autodiscover since it would reset the registry admin.autodiscover = lambda: None site = RestrictiveAdminSite() # copy over the autodiscovery site._registry = copy(admin.site._registry) # clear the default site registry to avoid leaking an insecure admin admin.site._registry = {} # rebind our admin site to maintain compatibility admin.site = site return site
def __new__(cls, name, bases, attrs): model = attrs.pop("model", None) form = attrs.pop("form", None) admin = attrs.pop("admin", None) admin_site = attrs.pop("admin_site", None) cls = super(SerializerMeta, cls).__new__(cls, name, bases, attrs) meta_klass = type( "Meta", (object,), { "model": model, "fields": "__all__", "form": form, "admin": admin, "admin_site": admin_site } ) setattr(cls, "Meta", meta_klass) return cls
def create_pattern(view, path, func_name): ptn = url(path, admin.site.admin_view(getattr(view, func_name))) return patterns('', ptn,)
def __init__(self, django_site, name='admino'): self.django_site = django_site self._registry = {} self.name = name self._actions = {'delete_selected': actions.delete_selected} self._global_actions = self._actions.copy()
def activated(self): django_admin_registered_apps = self.django_site._registry for model, admin_obj in django_admin_registered_apps.items(): mixin_class = AdminoMixin if hasattr(settings, "ADMINO_MIXIN_CLASS"): module_path = getattr(settings, "ADMINO_MIXIN_CLASS") mixin_class = import_from_string(module_path) django_admin_class = admin_obj.__class__ admino_class = type("ModelAdmino", (mixin_class, django_admin_class), {"admin_type": "admino"}) admino_obj = admino_class(model, self) self._registry[model] = admino_obj django_admin_autodiscover() return self
def test_datefilter(self): self.request_factory = RequestFactory() modeladmin = MyModelAdmin(MyModel, site) request = self.request_factory.get('/') changelist = self.get_changelist(request, MyModel, modeladmin) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.djangonaut_book, self.django_book]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_text(filterspec.title), 'created at')
def test_datetimfilter(self): self.request_factory = RequestFactory() modeladmin = MyModelTimeAdmin(MyModel, site) request = self.request_factory.get('/') changelist = self.get_changelist(request, MyModel, modeladmin) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.djangonaut_book, self.django_book]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_text(filterspec.title), 'created at')
def test_preferences_class_prepared(self): """ Regardless of what happens in the background, after startup and model preparation the preferences.preferences object should have members for each of the various preferences models. When accessing the member the appropriate object for the current site should be returned (or unassociated with a site if not using sites). """ # Should have MyPreferences member without # sites since we are not using sites. my_preferences = preferences.MyPreferences self.failIf(my_preferences.sites.all(), "Without SITE_ID should not \ have any preferences with sites.") # Should have MyPreferences member for current site. settings.SITE_ID = 1 current_site = Site.objects.get_current() my_preferences = preferences.MyPreferences self.failUnlessEqual(current_site, my_preferences.sites.get(), "With \ SITE_ID should have preferences for current site.") # Should have MyPreferences member for current site. settings.SITE_ID = 2 second_site, created = Site.objects.get_or_create(id=2) my_preferences = preferences.MyPreferences self.failUnlessEqual(second_site, my_preferences.sites.get(), "With \ SITE_ID should have preferences for current site.")
def test_site_cleanup(self): """ There should only ever be a single preferences object per site. Thus on many to many changes pre-existing preferences should be cleared of sites already associated with current preferences object. """ # When creating new preferences for a site, said site should be # removed from existing preference sites. site1 = Site.objects.create(domain="testserver") site2 = Site.objects.create(domain="another") # Add preferences for site 1. site1_preferences = MyPreferences.objects.create() site1_preferences.sites.add(site1) self.failUnlessEqual(site1_preferences.sites.get(), site1) # Now if we add another preferences object for site1, original site1 # preferences should no longer be associated with site1. more_site1_preferences = MyPreferences.objects.create() more_site1_preferences.sites.add(site1) self.failIf(site1 in site1_preferences.sites.all()) # If we add more sites to a preference, # it should be associated with them all. more_site1_preferences.sites.add(site2) self.failIf(site1 not in more_site1_preferences.sites.all() or site2 not in more_site1_preferences.sites.all()) some_more_preferences = MyPreferences.objects.create() some_more_preferences.sites.add(site1) some_more_preferences.sites.add(site2) self.failIf(site1 in more_site1_preferences.sites.all() or site2 in more_site1_preferences.sites.all()) # Double check that we now only have a single # preferences object associated with both sites. self.failUnlessEqual(MyPreferences.objects.filter(sites__in=[site1, site2]).distinct().get(), some_more_preferences)
def get_form(self, form_class): form = super(periodictaskcreate, self).get_form(form_class) rel_model = form.Meta.model rel = rel_model._meta.get_field('crontab').rel irel = rel_model._meta.get_field('interval').rel form.fields['crontab'].widget = RelatedFieldWidgetWrapper(form.fields['crontab'].widget, rel, admin.site, can_add_related=True, can_change_related=True) form.fields['interval'].widget = RelatedFieldWidgetWrapper(form.fields['interval'].widget, irel, admin.site, can_add_related=True, can_change_related=True) return form
def get_form(self, form_class): form = super(periodictaskupdate, self).get_form(form_class) rel_model = form.Meta.model rel = rel_model._meta.get_field('crontab').rel irel = rel_model._meta.get_field('interval').rel form.fields['crontab'].widget = RelatedFieldWidgetWrapper(form.fields['crontab'].widget, rel, admin.site, can_add_related=True, can_change_related=True) form.fields['interval'].widget = RelatedFieldWidgetWrapper(form.fields['interval'].widget, irel, admin.site, can_add_related=True, can_change_related=True) return form
def test_child_slug_collision(self): """ Test a slug collision """ root = create_page("home", 'nav_playground.html', "en", published=True) page = create_page("page", 'nav_playground.html', "en") subPage = create_page("subpage", 'nav_playground.html', "en", parent=page) create_page("child-page", 'nav_playground.html', "en", parent=root) superuser = self.get_superuser() with self.login_user_context(superuser): response = self.client.get(URL_CMS_PAGE_ADD+"?target=%s&position=right&site=1" % subPage.pk) self.assertContains(response, 'value="%s"' % page.pk) # slug collision between two child pages of the same node page_data = self.get_new_page_data(page.pk) page_data['slug'] = 'subpage' response = self.client.post(URL_CMS_PAGE_ADD, page_data) self.assertEqual(response.status_code, 200) self.assertTrue(response.request['PATH_INFO'].endswith(URL_CMS_PAGE_ADD)) self.assertContains(response, '<ul class="errorlist"><li>Another page with this slug already exists</li></ul>') # slug collision between page with no parent and a child page of root page_data = self.get_new_page_data() page_data['slug'] = 'child-page' response = self.client.post(URL_CMS_PAGE_ADD, page_data) self.assertEqual(response.status_code, 200) self.assertTrue(response.request['PATH_INFO'].endswith(URL_CMS_PAGE_ADD)) self.assertContains(response, '<ul class="errorlist"><li>Another page with this slug already exists</li></ul>') # slug collision between two top-level pages page_data = self.get_new_page_data() page_data['slug'] = 'page' response = self.client.post(URL_CMS_PAGE_ADD, page_data) self.assertEqual(response.status_code, 200) self.assertTrue(response.request['PATH_INFO'].endswith(URL_CMS_PAGE_ADD)) self.assertContains(response, '<ul class="errorlist"><li>Another page with this slug already exists</li></ul>')
def test_slug_collisions_api_1(self): """ Checks for slug collisions on sibling pages - uses API to create pages """ page1 = create_page('test page 1', 'nav_playground.html', 'en', published=True) page1_1 = create_page('test page 1_1', 'nav_playground.html', 'en', published=True, parent=page1, slug="foo") page1_2 = create_page('test page 1_2', 'nav_playground.html', 'en', published=True, parent=page1, slug="foo") # both sibling pages has same slug, so both pages has an invalid slug self.assertFalse(is_valid_page_slug(page1_1, page1_1.parent, "en", page1_1.get_slug("en"), page1_1.site)) self.assertFalse(is_valid_page_slug(page1_2, page1_2.parent, "en", page1_2.get_slug("en"), page1_2.site))
def test_slug_collisions_api_2(self): """ Checks for slug collisions on root (not home) page and a home page child - uses API to create pages """ page1 = create_page('test page 1', 'nav_playground.html', 'en', published=True) page1_1 = create_page('test page 1_1', 'nav_playground.html', 'en', published=True, parent=page1, slug="foo") page2 = create_page('test page 1_1', 'nav_playground.html', 'en', published=True, slug="foo") # Root (non home) page and child page has the same slug, both are invalid self.assertFalse(is_valid_page_slug(page1_1, page1_1.parent, "en", page1_1.get_slug("en"), page1_1.site)) self.assertFalse(is_valid_page_slug(page2, page2.parent, "en", page2.get_slug("en"), page2.site))
def test_existing_overwrite_url(self): with self.settings(CMS_PERMISSION=False): create_page('home', 'nav_playground.html', 'en', published=True) create_page('boo', 'nav_playground.html', 'en', published=True) data = { 'title': 'foo', 'overwrite_url': '/boo/', 'slug': 'foo', 'language': 'en', 'template': 'nav_playground.html', 'site': 1, } form = AdvancedSettingsForm(data) self.assertFalse(form.is_valid()) self.assertTrue('overwrite_url' in form.errors)
def test_valid_url_multisite(self): site1 = Site.objects.get_current() site3 = Site.objects.create(domain="sample3.com", name="sample3.com") home = create_page('home', 'nav_playground.html', 'de', published=True, site=site1) bar = create_page('bar', 'nav_playground.html', 'de', slug="bar", published=True, parent=home, site=site1) home_s3 = create_page('home', 'nav_playground.html', 'de', published=True, site=site3) bar_s3 = create_page('bar', 'nav_playground.html', 'de', slug="bar", published=True, parent=home_s3, site=site3) self.assertTrue(is_valid_url(bar.get_absolute_url('de'), bar)) self.assertTrue(is_valid_url(bar_s3.get_absolute_url('de'), bar_s3))
def get_page(self, parent=None, site=None, language=None, template='nav_playground.html'): page_data = { 'title': 'test page %d' % self.counter, 'slug': 'test-page-%d' % self.counter, 'language': settings.LANGUAGES[0][0] if not language else language, 'template': template, 'parent': parent if parent else None, 'site': site if site else Site.objects.get_current(), } page_data = self.get_new_page_data_dbfields() return create_page(**page_data)
def get_admin(self): """ Returns a PageAdmin instance. """ return PageAdmin(Page, admin.site)
def test_multisite(self): firstsite = Site.objects.create(name='first', domain='first.com') secondsite = Site.objects.create(name='second', domain='second.com') home = create_page('home', 'nav_playground.html', 'de', site=firstsite) home.publish('de') other = create_page('other', 'nav_playground.html', 'de', site=secondsite) other.publish('de') other = Page.objects.get(pk=other.pk) home = Page.objects.get(pk=home.pk) self.assertEqual(other.get_previous_filtered_sibling(), None) self.assertEqual(home.get_previous_filtered_sibling(), None)
def test_simple_context(self): class MyPlugin(CMSPluginBase): render_template = 'base.html' plugin = MyPlugin(ArticlePluginModel, admin.site) context = {} out_context = plugin.render(context, 1, 2) self.assertEqual(out_context['instance'], 1) self.assertEqual(out_context['placeholder'], 2) self.assertIs(out_context, context)
def test_thread_change_list_view__normal_case__correct_template_response(self, _): changelist_url = reverse( '{admin_site_name}:{app_label}_{model_name}_changelist'.format( admin_site_name=admin.site.name, app_label=Thread._meta.app_label, model_name=Thread._meta.model_name )) request = RequestFactory().get(changelist_url, follow=True) request.user = MockSuperUser() response = ThreadAdmin(Thread, admin.site).changelist_view(request) # what to test: # 1. template is admin/change_list.html and its subclass template # 2. status code 200 # 3. thread objects == response # They should be tested together # All objects qs = Thread.objects.filter() template_names = set([ 'admin/change_list.html', 'admin/disqus_backstore/change_list.html', 'admin/disqus_backstore/thread/change_list.html', ]) self.assertEqual(response.status_code, 200) self.assertEqual(set(response.template_name), template_names) self.assertEqual(list(response.context_data['cl'].result_list), list(qs))
def test_post_change_list_view__normal_case__correct_template_response(self, _, __): changelist_url = reverse( '{admin_site_name}:{app_label}_{model_name}_changelist'.format( admin_site_name=admin.site.name, app_label=Post._meta.app_label, model_name=Post._meta.model_name )) request = RequestFactory().get(changelist_url, follow=True) request.user = MockSuperUser() response = PostAdmin(Post, admin.site).changelist_view(request) # what to test: # 1. template is admin/change_list.html and its subclass template # 2. status code 200 # 3. thread objects == response # They should be tested together # All objects qs = Post.objects.filter() template_names = set([ 'admin/change_list.html', 'admin/disqus_backstore/change_list.html', 'admin/disqus_backstore/post/change_list.html', ]) self.assertEqual(response.status_code, 200) self.assertEqual(set(response.template_name), template_names) self.assertEqual(list(response.context_data['cl'].result_list), list(qs))
def test_thread_change_form_view__normal_case__correct_template_response(self, _): thread_data = SINGLE_THREAD_LIST_RESPONSE['response'][0] thread_object = thread_factory(thread_data) change_url = reverse('{admin_site_name}:{app_label}_{model_name}_change'.format( admin_site_name=admin.site.name, app_label=Thread._meta.app_label, model_name=Thread._meta.model_name ), args=[thread_object.id]) request = RequestFactory().get(change_url, follow=True) request.user = MockSuperUser() response = ThreadAdmin(Thread, admin.site).change_view(request, thread_data['id']) # what to test: # 1. template is admin/change_form.html and its subclass template # 2. status code 200 # 3. thread object id is equal to the form bounded value # (So they are the same one.) # They should be tested together # All objects template_names = set([ 'admin/change_form.html', 'admin/disqus_backstore/change_form.html', 'admin/disqus_backstore/thread/change_form.html', ]) self.assertEqual(response.status_code, 200) self.assertEqual(set(response.template_name), template_names) self.assertEqual( response.context_data['adminform'].form['id'].value(), thread_object.id )
def test_thread_delete_view__get__success(self, _, __): thread_data = THREADS_LIST_RESPONSE['response'][0] post_data = POSTS_LIST_RESPONSE['response'][0] thread_object = thread_factory(thread_data) related_post_object = post_factory(post_data) related_post_object.thread = thread_object delete_url = reverse('{admin_site_name}:{app_label}_{model_name}_delete'.format( admin_site_name=admin.site.name, app_label=Thread._meta.app_label, model_name=Thread._meta.model_name ), args=[thread_object.id]) request = RequestFactory().get(delete_url, follow=True) request.user = MockSuperUser() response = ThreadAdmin(Thread, admin.site).delete_view(request, str(thread_object.id)) template_names = set([ 'admin/delete_confirmation.html', 'admin/disqus_backstore/delete_confirmation.html', 'admin/disqus_backstore/thread/delete_confirmation.html', ]) self.assertEqual(response.status_code, 200) self.assertEqual(set(response.template_name), template_names) # dirty hack for formatting deleted_object context... Use the same formatting # in django.contrib.admin.utils.get_deleted_objects # the related post objects will be a list of post object, # so we have to put it into a list... deleted_objects = [format_html('{}: <a href="{}">{}</a>', capfirst(obj.__class__._meta.verbose_name), reverse('%s:%s_%s_change' % ( admin.site.name, obj._meta.app_label, obj._meta.model_name ), None, (quote(obj._get_pk_val()),)), obj) for obj in [thread_object, related_post_object]] deleted_objects[1] = [deleted_objects[1]] self.assertEqual(sorted(response.context_data['deleted_objects']), sorted(deleted_objects))
def test_post_delete_view__get__success(self, _, __): thread_data = THREADS_LIST_RESPONSE['response'][0] post_data = POSTS_LIST_RESPONSE['response'][0] thread_object = thread_factory(thread_data) post_object = post_factory(post_data) post_object.thread = thread_object delete_url = reverse('{admin_site_name}:{app_label}_{model_name}_delete'.format( admin_site_name=admin.site.name, app_label=Post._meta.app_label, model_name=Post._meta.model_name ), args=[post_data['id']]) request = RequestFactory().get(delete_url, follow=True) request.user = MockSuperUser() response = PostAdmin(Post, admin.site).delete_view(request, post_data['id']) template_names = set([ 'admin/delete_confirmation.html', 'admin/disqus_backstore/delete_confirmation.html', 'admin/disqus_backstore/post/delete_confirmation.html', ]) self.assertEqual(response.status_code, 200) self.assertEqual(set(response.template_name), template_names) # dirty hack for formatting deleted_object context... Use the same formatting # in django.contrib.admin.utils.get_deleted_objects deleted_objects = [format_html('{}: <a href="{}">{}</a>', capfirst(obj.__class__._meta.verbose_name), reverse('%s:%s_%s_change' % ( admin.site.name, obj._meta.app_label, obj._meta.model_name ), None, (quote(obj._get_pk_val()),)), obj) for obj in [post_object]] self.assertEqual(response.context_data['deleted_objects'], deleted_objects)
def test_post_delete_view__post__success(self, _, __, delete_post_mock): thread_data = THREADS_LIST_RESPONSE['response'][0] post_data = POSTS_LIST_RESPONSE['response'][0] thread_object = thread_factory(thread_data) post_object = post_factory(post_data) post_object.thread = thread_object deleteuser = User.objects.create_user( username='deleteuser', password='secret', is_staff=True ) deleteuser.user_permissions.add( get_perm( Thread, get_permission_codename('delete', Thread._meta) ) ) deleteuser.user_permissions.add( get_perm( Post, get_permission_codename('delete', Post._meta) ) ) self.client.force_login(deleteuser) delete_url = reverse('{admin_site_name}:{app_label}_{model_name}_delete'.format( admin_site_name=admin.site.name, app_label=Post._meta.app_label, model_name=Post._meta.model_name ), args=[post_data['id']]) delete_dict = {'post': 'yes'} response = self.client.post(delete_url, delete_dict) self.assertEqual(response.status_code, 302) delete_post_mock.assert_called_once_with(post_object.id)
def ready(self): if not isinstance(admin.site, AdminViewPermissionAdminSite): admin.site = AdminViewPermissionAdminSite('admin') admin.sites.site = admin.site post_migrate.connect(update_permissions)
def setUp(self): self.modeladmin = AlertAdmin(Alert, admin.site) self.modeladmin.message_user = Mock() self.queryset_single = Mock() self.queryset_single.update = Mock(return_value=1) self.queryset_multi = Mock() self.queryset_multi.update = Mock(return_value=2) self.request = Mock()
def patch_admin(model, admin_site=None): """ Enables version control with full admin integration for a model that has already been registered with the django admin site. This is excellent for adding version control to existing Django contrib applications. """ admin_site = admin_site or admin.site try: ModelAdmin = admin_site._registry[model].__class__ except KeyError: raise NotRegistered("The model {model} has not been registered with the admin site.".format( model = model, )) # Unregister existing admin class. admin_site.unregister(model) # Register patched admin class. class PatchedModelAdmin(VersionAdmin, ModelAdmin): pass admin_site.register(model, PatchedModelAdmin) # Patch generation methods, only available if the google-diff-match-patch # library is installed. # # http://code.google.com/p/google-diff-match-patch/
def form_class(self): form_klass = getattr(self.Meta, "form", None) admin_klass = getattr(self.Meta, "admin", None) admin_site = getattr(self.Meta, "admin_site", None) if admin_klass: if not admin_site: # Fall back to default from django.contrib.admin import site as admin_site return admin_klass(self.Meta.model, admin_site).get_form( self.context["request"], self.initial ) elif form_klass: return form_klass return None