# coding: utf-8 from __future__ import absolute_import, unicode_literals import os import re import datetime try: from urllib.parse import urljoin except ImportError: # Python 2 from urlparse import urljoin from django.conf import settings, global_settings from django.core import mail from django.core.files import temp as tempfile from django.core.urlresolvers import reverse # Register auth models with the admin. from django.contrib import admin from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.models import LogEntry, DELETION from django.contrib.admin.sites import LOGIN_FORM_KEY from django.contrib.admin.util import quote from django.contrib.admin.views.main import IS_POPUP_VAR from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.models import Group, User, Permission from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.db import connection from django.forms.util import ErrorList from django.template.response import TemplateResponse from django.test import TestCase from django.test.utils import patch_logger from django.utils import formats, translation, unittest from django.utils.cache import get_max_age from django.utils.encoding import iri_to_uri, force_bytes from django.utils.html import escape from django.utils.http import urlencode, urlquote from django.utils._os import upath from django.utils import six from django.test.utils import override_settings # local test models from .models import (Article, BarAccount, CustomArticle, EmptyModel, FooAccount, Gallery, ModelWithStringPrimaryKey, Person, Persona, Picture, Podcast, Section, Subscriber, Vodcast, Language, Collector, Widget, Grommet, DooHickey, FancyDoodad, Whatsit, Category, Post, Plot, FunkyTag, Chapter, Book, Promo, WorkHour, Employee, Question, Answer, Inquisition, Actor, FoodDelivery, RowLevelChangePermissionModel, Paper, CoverLetter, Story, OtherStory, ComplexSortedPerson, PluggableSearchPerson, Parent, Child, AdminOrderedField, AdminOrderedModelMethod, AdminOrderedAdminMethod, AdminOrderedCallable, Report, MainPrepopulated, RelatedPrepopulated, UnorderedObject, Simple, UndeletableObject, Choice, ShortMessage, Telegram) ERROR_MESSAGE = "Please enter the correct username and password \ for a staff account. Note that both fields may be case-sensitive." @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminViewBasicTest(TestCase): fixtures = ['admin-views-users.xml', 'admin-views-colors.xml', 'admin-views-fabrics.xml', 'admin-views-books.xml'] # Store the bit of the URL where the admin is registered as a class # variable. That way we can test a second AdminSite just by subclassing # this test case and changing urlbit. urlbit = 'admin' urls = "admin_views.urls" def setUp(self): self.old_USE_I18N = settings.USE_I18N self.old_USE_L10N = settings.USE_L10N self.old_LANGUAGE_CODE = settings.LANGUAGE_CODE self.client.login(username='super', password='secret') settings.USE_I18N = True def tearDown(self): settings.USE_I18N = self.old_USE_I18N settings.USE_L10N = self.old_USE_L10N settings.LANGUAGE_CODE = self.old_LANGUAGE_CODE self.client.logout() formats.reset_format_cache() def assertContentBefore(self, response, text1, text2, failing_msg=None): """ Testing utility asserting that text1 appears before text2 in response content. """ self.assertEqual(response.status_code, 200) self.assertTrue(response.content.index(force_bytes(text1)) < response.content.index(force_bytes(text2)), failing_msg ) def testTrailingSlashRequired(self): """ If you leave off the trailing slash, app should redirect and add it. """ response = self.client.get('/test_admin/%s/admin_views/article/add' % self.urlbit) self.assertRedirects(response, '/test_admin/%s/admin_views/article/add/' % self.urlbit, status_code=301 ) def testBasicAddGet(self): """ A smoke test to ensure GET on the add_view works. """ response = self.client.get('/test_admin/%s/admin_views/section/add/' % self.urlbit) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def testAddWithGETArgs(self): response = self.client.get('/test_admin/%s/admin_views/section/add/' % self.urlbit, {'name': 'My Section'}) self.assertEqual(response.status_code, 200) self.assertContains(response, 'value="My Section"', msg_prefix="Couldn't find an input with the right value in the response" ) def testBasicEditGet(self): """ A smoke test to ensure GET on the change_view works. """ response = self.client.get('/test_admin/%s/admin_views/section/1/' % self.urlbit) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def testBasicEditGetStringPK(self): """ Ensure GET on the change_view works (returns an HTTP 404 error, see #11191) when passing a string as the PK argument for a model with an integer PK field. """ response = self.client.get('/test_admin/%s/admin_views/section/abc/' % self.urlbit) self.assertEqual(response.status_code, 404) def testBasicInheritanceGetStringPK(self): """ Ensure GET on the change_view works on inherited models (returns an HTTP 404 error, see #19951) when passing a string as the PK argument for a model with an integer PK field. """ response = self.client.get('/test_admin/%s/admin_views/supervillain/abc/' % self.urlbit) self.assertEqual(response.status_code, 404) def testBasicAddPost(self): """ A smoke test to ensure POST on add_view works. """ post_data = { "name": "Another Section", # inline data "article_set-TOTAL_FORMS": "3", "article_set-INITIAL_FORMS": "0", "article_set-MAX_NUM_FORMS": "0", } response = self.client.post('/test_admin/%s/admin_views/section/add/' % self.urlbit, post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def testPopupAddPost(self): """ Ensure http response from a popup is properly escaped. """ post_data = { '_popup': '1', 'title': 'title with a new\nline', 'content': 'some content', 'date_0': '2010-09-10', 'date_1': '14:55:39', } response = self.client.post('/test_admin/%s/admin_views/article/add/' % self.urlbit, post_data) self.assertEqual(response.status_code, 200) self.assertContains(response, 'dismissAddAnotherPopup') self.assertContains(response, 'title with a new\\u000Aline') # Post data for edit inline inline_post_data = { "name": "Test section", # inline data "article_set-TOTAL_FORMS": "6", "article_set-INITIAL_FORMS": "3", "article_set-MAX_NUM_FORMS": "0", "article_set-0-id": "1", # there is no title in database, give one here or formset will fail. "article_set-0-title": "Norske bostaver æøå skaper problemer", "article_set-0-content": "<p>Middle content</p>", "article_set-0-date_0": "2008-03-18", "article_set-0-date_1": "11:54:58", "article_set-0-section": "1", "article_set-1-id": "2", "article_set-1-title": "Need a title.", "article_set-1-content": "<p>Oldest content</p>", "article_set-1-date_0": "2000-03-18", "article_set-1-date_1": "11:54:58", "article_set-2-id": "3", "article_set-2-title": "Need a title.", "article_set-2-content": "<p>Newest content</p>", "article_set-2-date_0": "2009-03-18", "article_set-2-date_1": "11:54:58", "article_set-3-id": "", "article_set-3-title": "", "article_set-3-content": "", "article_set-3-date_0": "", "article_set-3-date_1": "", "article_set-4-id": "", "article_set-4-title": "", "article_set-4-content": "", "article_set-4-date_0": "", "article_set-4-date_1": "", "article_set-5-id": "", "article_set-5-title": "", "article_set-5-content": "", "article_set-5-date_0": "", "article_set-5-date_1": "", } def testBasicEditPost(self): """ A smoke test to ensure POST on edit_view works. """ response = self.client.post('/test_admin/%s/admin_views/section/1/' % self.urlbit, self.inline_post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def testEditSaveAs(self): """ Test "save as". """ post_data = self.inline_post_data.copy() post_data.update({ '_saveasnew': 'Save+as+new', "article_set-1-section": "1", "article_set-2-section": "1", "article_set-3-section": "1", "article_set-4-section": "1", "article_set-5-section": "1", }) response = self.client.post('/test_admin/%s/admin_views/section/1/' % self.urlbit, post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def testChangeListSortingCallable(self): """ Ensure we can sort on a list_display field that is a callable (column 2 is callable_year in ArticleAdmin) """ response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit, {'o': 2}) self.assertContentBefore(response, 'Oldest content', 'Middle content', "Results of sorting on callable are out of order.") self.assertContentBefore(response, 'Middle content', 'Newest content', "Results of sorting on callable are out of order.") def testChangeListSortingModel(self): """ Ensure we can sort on a list_display field that is a Model method (colunn 3 is 'model_year' in ArticleAdmin) """ response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit, {'o': '-3'}) self.assertContentBefore(response, 'Newest content', 'Middle content', "Results of sorting on Model method are out of order.") self.assertContentBefore(response, 'Middle content', 'Oldest content', "Results of sorting on Model method are out of order.") def testChangeListSortingModelAdmin(self): """ Ensure we can sort on a list_display field that is a ModelAdmin method (colunn 4 is 'modeladmin_year' in ArticleAdmin) """ response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit, {'o': '4'}) self.assertContentBefore(response, 'Oldest content', 'Middle content', "Results of sorting on ModelAdmin method are out of order.") self.assertContentBefore(response, 'Middle content', 'Newest content', "Results of sorting on ModelAdmin method are out of order.") def testChangeListSortingMultiple(self): p1 = Person.objects.create(name="Chris", gender=1, alive=True) p2 = Person.objects.create(name="Chris", gender=2, alive=True) p3 = Person.objects.create(name="Bob", gender=1, alive=True) link1 = reverse('admin:admin_views_person_change', args=(p1.pk,)) link2 = reverse('admin:admin_views_person_change', args=(p2.pk,)) link3 = reverse('admin:admin_views_person_change', args=(p3.pk,)) # Sort by name, gender # This hard-codes the URL because it'll fail if it runs against the # 'admin2' custom admin (which doesn't have the Person model). response = self.client.get('/test_admin/admin/admin_views/person/', {'o': '1.2'}) self.assertContentBefore(response, link3, link1) self.assertContentBefore(response, link1, link2) # Sort by gender descending, name response = self.client.get('/test_admin/admin/admin_views/person/', {'o': '-2.1'}) self.assertContentBefore(response, link2, link3) self.assertContentBefore(response, link3, link1) def testChangeListSortingPreserveQuerySetOrdering(self): """ If no ordering is defined in `ModelAdmin.ordering` or in the query string, then the underlying order of the queryset should not be changed, even if it is defined in `Modeladmin.get_queryset()`. Refs #11868, #7309. """ p1 = Person.objects.create(name="Amy", gender=1, alive=True, age=80) p2 = Person.objects.create(name="Bob", gender=1, alive=True, age=70) p3 = Person.objects.create(name="Chris", gender=2, alive=False, age=60) link1 = reverse('admin:admin_views_person_change', args=(p1.pk,)) link2 = reverse('admin:admin_views_person_change', args=(p2.pk,)) link3 = reverse('admin:admin_views_person_change', args=(p3.pk,)) # This hard-codes the URL because it'll fail if it runs against the # 'admin2' custom admin (which doesn't have the Person model). response = self.client.get('/test_admin/admin/admin_views/person/', {}) self.assertContentBefore(response, link3, link2) self.assertContentBefore(response, link2, link1) def testChangeListSortingModelMeta(self): # Test ordering on Model Meta is respected l1 = Language.objects.create(iso='ur', name='Urdu') l2 = Language.objects.create(iso='ar', name='Arabic') link1 = reverse('admin:admin_views_language_change', args=(quote(l1.pk),)) link2 = reverse('admin:admin_views_language_change', args=(quote(l2.pk),)) response = self.client.get('/test_admin/admin/admin_views/language/', {}) self.assertContentBefore(response, link2, link1) # Test we can override with query string response = self.client.get('/test_admin/admin/admin_views/language/', {'o': '-1'}) self.assertContentBefore(response, link1, link2) def testChangeListSortingOverrideModelAdmin(self): # Test ordering on Model Admin is respected, and overrides Model Meta dt = datetime.datetime.now() p1 = Podcast.objects.create(name="A", release_date=dt) p2 = Podcast.objects.create(name="B", release_date=dt - datetime.timedelta(10)) link1 = reverse('admin:admin_views_podcast_change', args=(p1.pk,)) link2 = reverse('admin:admin_views_podcast_change', args=(p2.pk,)) response = self.client.get('/test_admin/admin/admin_views/podcast/', {}) self.assertContentBefore(response, link1, link2) def testMultipleSortSameField(self): # Check that we get the columns we expect if we have two columns # that correspond to the same ordering field dt = datetime.datetime.now() p1 = Podcast.objects.create(name="A", release_date=dt) p2 = Podcast.objects.create(name="B", release_date=dt - datetime.timedelta(10)) link1 = reverse('admin:admin_views_podcast_change', args=(quote(p1.pk),)) link2 = reverse('admin:admin_views_podcast_change', args=(quote(p2.pk),)) response = self.client.get('/test_admin/admin/admin_views/podcast/', {}) self.assertContentBefore(response, link1, link2) p1 = ComplexSortedPerson.objects.create(name="Bob", age=10) p2 = ComplexSortedPerson.objects.create(name="Amy", age=20) link1 = reverse('admin:admin_views_complexsortedperson_change', args=(p1.pk,)) link2 = reverse('admin:admin_views_complexsortedperson_change', args=(p2.pk,)) response = self.client.get('/test_admin/admin/admin_views/complexsortedperson/', {}) # Should have 5 columns (including action checkbox col) self.assertContains(response, '', msg_prefix="Expected filter not found in changelist view" ) self.assertNotContains(response, 'Blue', msg_prefix="Changelist filter not correctly limited by limit_choices_to" ) def testRelationSpanningFilters(self): response = self.client.get('/test_admin/%s/admin_views/chapterxtra1/' % self.urlbit) self.assertEqual(response.status_code, 200) self.assertContains(response, '
') filters = { 'chap__id__exact': dict( values=[c.id for c in Chapter.objects.all()], test=lambda obj, value: obj.chap.id == value), 'chap__title': dict( values=[c.title for c in Chapter.objects.all()], test=lambda obj, value: obj.chap.title == value), 'chap__book__id__exact': dict( values=[b.id for b in Book.objects.all()], test=lambda obj, value: obj.chap.book.id == value), 'chap__book__name': dict( values=[b.name for b in Book.objects.all()], test=lambda obj, value: obj.chap.book.name == value), 'chap__book__promo__id__exact': dict( values=[p.id for p in Promo.objects.all()], test=lambda obj, value: obj.chap.book.promo_set.filter(id=value).exists()), 'chap__book__promo__name': dict( values=[p.name for p in Promo.objects.all()], test=lambda obj, value: obj.chap.book.promo_set.filter(name=value).exists()), } for filter_path, params in filters.items(): for value in params['values']: query_string = urlencode({filter_path: value}) # ensure filter link exists self.assertContains(response, '' % query_string) # ensure link works filtered_response = self.client.get( '/test_admin/%s/admin_views/chapterxtra1/?%s' % ( self.urlbit, query_string)) self.assertEqual(filtered_response.status_code, 200) # ensure changelist contains only valid objects for obj in filtered_response.context['cl'].queryset.all(): self.assertTrue(params['test'](obj, value)) def testIncorrectLookupParameters(self): """Ensure incorrect lookup parameters are handled gracefully.""" response = self.client.get('/test_admin/%s/admin_views/thing/' % self.urlbit, {'notarealfield': '5'}) self.assertRedirects(response, '/test_admin/%s/admin_views/thing/?e=1' % self.urlbit) # Spanning relationships through an inexistant related object (Refs #16716) response = self.client.get('/test_admin/%s/admin_views/thing/' % self.urlbit, {'notarealfield__whatever': '5'}) self.assertRedirects(response, '/test_admin/%s/admin_views/thing/?e=1' % self.urlbit) response = self.client.get('/test_admin/%s/admin_views/thing/' % self.urlbit, {'color__id__exact': 'StringNotInteger!'}) self.assertRedirects(response, '/test_admin/%s/admin_views/thing/?e=1' % self.urlbit) # Regression test for #18530 response = self.client.get('/test_admin/%s/admin_views/thing/' % self.urlbit, {'pub_date__gte': 'foo'}) self.assertRedirects(response, '/test_admin/%s/admin_views/thing/?e=1' % self.urlbit) def testIsNullLookups(self): """Ensure is_null is handled correctly.""" Article.objects.create(title="I Could Go Anywhere", content="Versatile", date=datetime.datetime.now()) response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit) self.assertContains(response, '4 articles') response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit, {'section__isnull': 'false'}) self.assertContains(response, '3 articles') response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit, {'section__isnull': '0'}) self.assertContains(response, '3 articles') response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit, {'section__isnull': 'true'}) self.assertContains(response, '1 article') response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit, {'section__isnull': '1'}) self.assertContains(response, '1 article') def testLogoutAndPasswordChangeURLs(self): response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit) self.assertContains(response, '' % self.urlbit) self.assertContains(response, '' % self.urlbit) def testNamedGroupFieldChoicesChangeList(self): """ Ensures the admin changelist shows correct values in the relevant column for rows corresponding to instances of a model in which a named group has been used in the choices option of a field. """ link1 = reverse('admin:admin_views_fabric_change', args=(1,), current_app=self.urlbit) link2 = reverse('admin:admin_views_fabric_change', args=(2,), current_app=self.urlbit) response = self.client.get('/test_admin/%s/admin_views/fabric/' % self.urlbit) fail_msg = "Changelist table isn't showing the right human-readable values set by a model field 'choices' option named group." self.assertContains(response, 'Horizontal' % link1, msg_prefix=fail_msg, html=True) self.assertContains(response, 'Vertical' % link2, msg_prefix=fail_msg, html=True) def testNamedGroupFieldChoicesFilter(self): """ Ensures the filter UI shows correctly when at least one named group has been used in the choices option of a model field. """ response = self.client.get('/test_admin/%s/admin_views/fabric/' % self.urlbit) fail_msg = "Changelist filter isn't showing options contained inside a model field 'choices' option named group." self.assertContains(response, '
') self.assertContains(response, 'Horizontal', msg_prefix=fail_msg, html=True) self.assertContains(response, 'Vertical', msg_prefix=fail_msg, html=True) def testChangeListNullBooleanDisplay(self): Post.objects.create(public=None) # This hard-codes the URl because it'll fail if it runs # against the 'admin2' custom admin (which doesn't have the # Post model). response = self.client.get("/test_admin/admin/admin_views/post/") self.assertContains(response, 'icon-unknown.gif') def testI18NLanguageNonEnglishDefault(self): """ Check if the JavaScript i18n view returns an empty language catalog if the default language is non-English but the selected language is English. See #13388 and #3594 for more details. """ with self.settings(LANGUAGE_CODE='fr'): with translation.override('en-us'): response = self.client.get('/test_admin/admin/jsi18n/') self.assertNotContains(response, 'Choisir une heure') def testI18NLanguageNonEnglishFallback(self): """ Makes sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE='fr'): with translation.override('none'): response = self.client.get('/test_admin/admin/jsi18n/') self.assertContains(response, 'Choisir une heure') def testL10NDeactivated(self): """ Check if L10N is deactivated, the JavaScript i18n view doesn't return localized date/time formats. Refs #14824. """ with self.settings(LANGUAGE_CODE='ru', USE_L10N=False): with translation.override('none'): response = self.client.get('/test_admin/admin/jsi18n/') self.assertNotContains(response, '%d.%m.%Y %H:%M:%S') self.assertContains(response, '%Y-%m-%d %H:%M:%S') def test_disallowed_filtering(self): with patch_logger('django.security.DisallowedModelAdminLookup', 'error') as calls: response = self.client.get("/test_admin/admin/admin_views/album/?owner__email__startswith=fuzzy") self.assertEqual(response.status_code, 400) self.assertEqual(len(calls), 1) # Filters are allowed if explicitly included in list_filter response = self.client.get("/test_admin/admin/admin_views/thing/?color__value__startswith=red") self.assertEqual(response.status_code, 200) response = self.client.get("/test_admin/admin/admin_views/thing/?color__value=red") self.assertEqual(response.status_code, 200) # Filters should be allowed if they involve a local field without the # need to whitelist them in list_filter or date_hierarchy. response = self.client.get("/test_admin/admin/admin_views/person/?age__gt=30") self.assertEqual(response.status_code, 200) e1 = Employee.objects.create(name='Anonymous', gender=1, age=22, alive=True, code='123') e2 = Employee.objects.create(name='Visitor', gender=2, age=19, alive=True, code='124') WorkHour.objects.create(datum=datetime.datetime.now(), employee=e1) WorkHour.objects.create(datum=datetime.datetime.now(), employee=e2) response = self.client.get("/test_admin/admin/admin_views/workhour/") self.assertEqual(response.status_code, 200) self.assertContains(response, 'employee__person_ptr__exact') response = self.client.get("/test_admin/admin/admin_views/workhour/?employee__person_ptr__exact=%d" % e1.pk) self.assertEqual(response.status_code, 200) def test_allowed_filtering_15103(self): """ Regressions test for ticket 15103 - filtering on fields defined in a ForeignKey 'limit_choices_to' should be allowed, otherwise raw_id_fields can break. """ # Filters should be allowed if they are defined on a ForeignKey pointing to this model response = self.client.get("/test_admin/admin/admin_views/inquisition/?leader__name=Palin&leader__age=27") self.assertEqual(response.status_code, 200) def test_hide_change_password(self): """ Tests if the "change password" link in the admin is hidden if the User does not have a usable password set. (against 9bea85795705d015cdadc82c68b99196a8554f5c) """ user = User.objects.get(username='super') password = user.password user.set_unusable_password() user.save() response = self.client.get('/test_admin/admin/') self.assertNotContains(response, reverse('admin:password_change'), msg_prefix='The "change password" link should not be displayed if a user does not have a usable password.') def test_change_view_with_show_delete_extra_context(self): """ Ensured that the 'show_delete' context variable in the admin's change view actually controls the display of the delete button. Refs #10057. """ instance = UndeletableObject.objects.create(name='foo') response = self.client.get('/test_admin/%s/admin_views/undeletableobject/%d/' % (self.urlbit, instance.pk)) self.assertNotContains(response, 'deletelink') def test_allows_attributeerror_to_bubble_up(self): """ Ensure that AttributeErrors are allowed to bubble when raised inside a change list view. Requires a model to be created so there's something to be displayed Refs: #16655, #18593, and #18747 """ Simple.objects.create() with self.assertRaises(AttributeError): self.client.get('/test_admin/%s/admin_views/simple/' % self.urlbit) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminViewFormUrlTest(TestCase): urls = "admin_views.urls" fixtures = ["admin-views-users.xml"] urlbit = "admin3" def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def testChangeFormUrlHasCorrectValue(self): """ Tests whether change_view has form_url in response.context """ response = self.client.get('/test_admin/%s/admin_views/section/1/' % self.urlbit) self.assertTrue('form_url' in response.context, msg='form_url not present in response.context') self.assertEqual(response.context['form_url'], 'pony') def test_filter_with_custom_template(self): """ Ensure that one can use a custom template to render an admin filter. Refs #17515. """ template_dirs = settings.TEMPLATE_DIRS + ( os.path.join(os.path.dirname(upath(__file__)), 'templates'),) with self.settings(TEMPLATE_DIRS=template_dirs): response = self.client.get("/test_admin/admin/admin_views/color2/") self.assertTemplateUsed(response, 'custom_filter_template.html') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminJavaScriptTest(TestCase): fixtures = ['admin-views-users.xml'] urls = "admin_views.urls" def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def testSingleWidgetFirsFieldFocus(self): """ JavaScript-assisted auto-focus on first field. """ response = self.client.get('/test_admin/%s/admin_views/picture/add/' % 'admin') self.assertContains( response, '' ) def testMultiWidgetFirsFieldFocus(self): """ JavaScript-assisted auto-focus should work if a model/ModelAdmin setup is such that the first form field has a MultiWidget. """ response = self.client.get('/test_admin/%s/admin_views/reservation/add/' % 'admin') self.assertContains( response, '' ) def test_js_minified_only_if_debug_is_false(self): """ Ensure that the minified versions of the JS files are only used when DEBUG is False. Refs #17521. """ with override_settings(DEBUG=False): response = self.client.get( '/test_admin/%s/admin_views/section/add/' % 'admin') self.assertNotContains(response, 'jquery.js') self.assertContains(response, 'jquery.min.js') self.assertNotContains(response, 'prepopulate.js') self.assertContains(response, 'prepopulate.min.js') self.assertNotContains(response, 'actions.js') self.assertContains(response, 'actions.min.js') self.assertNotContains(response, 'collapse.js') self.assertContains(response, 'collapse.min.js') self.assertNotContains(response, 'inlines.js') self.assertContains(response, 'inlines.min.js') with override_settings(DEBUG=True): response = self.client.get( '/test_admin/%s/admin_views/section/add/' % 'admin') self.assertContains(response, 'jquery.js') self.assertNotContains(response, 'jquery.min.js') self.assertContains(response, 'prepopulate.js') self.assertNotContains(response, 'prepopulate.min.js') self.assertContains(response, 'actions.js') self.assertNotContains(response, 'actions.min.js') self.assertContains(response, 'collapse.js') self.assertNotContains(response, 'collapse.min.js') self.assertContains(response, 'inlines.js') self.assertNotContains(response, 'inlines.min.js') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class SaveAsTests(TestCase): urls = "admin_views.urls" fixtures = ['admin-views-users.xml', 'admin-views-person.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_save_as_duplication(self): """Ensure save as actually creates a new person""" post_data = {'_saveasnew': '', 'name': 'John M', 'gender': 1, 'age': 42} response = self.client.post('/test_admin/admin/admin_views/person/1/', post_data) self.assertEqual(len(Person.objects.filter(name='John M')), 1) self.assertEqual(len(Person.objects.filter(id=1)), 1) def test_save_as_display(self): """ Ensure that 'save as' is displayed when activated and after submitting invalid data aside save_as_new will not show us a form to overwrite the initial model. """ response = self.client.get('/test_admin/admin/admin_views/person/1/') self.assertTrue(response.context['save_as']) post_data = {'_saveasnew': '', 'name': 'John M', 'gender': 3, 'alive': 'checked'} response = self.client.post('/test_admin/admin/admin_views/person/1/', post_data) self.assertEqual(response.context['form_url'], '/test_admin/admin/admin_views/person/add/') class CustomModelAdminTest(AdminViewBasicTest): urls = "admin_views.urls" urlbit = "admin2" def testCustomAdminSiteLoginForm(self): self.client.logout() response = self.client.get('/test_admin/admin2/') self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) login = self.client.post('/test_admin/admin2/', { REDIRECT_FIELD_NAME: '/test_admin/admin2/', LOGIN_FORM_KEY: 1, 'username': 'customform', 'password': 'secret', }) self.assertIsInstance(login, TemplateResponse) self.assertEqual(login.status_code, 200) self.assertContains(login, 'custom form error') def testCustomAdminSiteLoginTemplate(self): self.client.logout() response = self.client.get('/test_admin/admin2/') self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, 'custom_admin/login.html') self.assertContains(response, 'Hello from a custom login template') def testCustomAdminSiteLogoutTemplate(self): response = self.client.get('/test_admin/admin2/logout/') self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, 'custom_admin/logout.html') self.assertContains(response, 'Hello from a custom logout template') def testCustomAdminSiteIndexViewAndTemplate(self): try: response = self.client.get('/test_admin/admin2/') except TypeError: self.fail('AdminSite.index_template should accept a list of template paths') self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, 'custom_admin/index.html') self.assertContains(response, 'Hello from a custom index template *bar*') def testCustomAdminSitePasswordChangeTemplate(self): response = self.client.get('/test_admin/admin2/password_change/') self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, 'custom_admin/password_change_form.html') self.assertContains(response, 'Hello from a custom password change form template') def testCustomAdminSitePasswordChangeDoneTemplate(self): response = self.client.get('/test_admin/admin2/password_change/done/') self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, 'custom_admin/password_change_done.html') self.assertContains(response, 'Hello from a custom password change done template') def testCustomAdminSiteView(self): self.client.login(username='super', password='secret') response = self.client.get('/test_admin/%s/my_view/' % self.urlbit) self.assertEqual(response.content, b"Django is a magical pony!") def test_pwd_change_custom_template(self): self.client.login(username='super', password='secret') su = User.objects.get(username='super') try: response = self.client.get('/test_admin/admin4/auth/user/%s/password/' % su.pk) except TypeError: self.fail('ModelAdmin.change_user_password_template should accept a list of template paths') self.assertEqual(response.status_code, 200) def get_perm(Model, perm): """Return the permission object, for the Model""" ct = ContentType.objects.get_for_model(Model) return Permission.objects.get(content_type=ct, codename=perm) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminViewPermissionsTest(TestCase): """Tests for Admin Views Permissions.""" urls = "admin_views.urls" fixtures = ['admin-views-users.xml'] def setUp(self): """Test setup.""" # Setup permissions, for our users who can add, change, and delete. # We can't put this into the fixture, because the content type id # and the permission id could be different on each run of the test. opts = Article._meta # User who can add Articles add_user = User.objects.get(username='adduser') add_user.user_permissions.add(get_perm(Article, opts.get_add_permission())) # User who can change Articles change_user = User.objects.get(username='changeuser') change_user.user_permissions.add(get_perm(Article, opts.get_change_permission())) # User who can delete Articles delete_user = User.objects.get(username='deleteuser') delete_user.user_permissions.add(get_perm(Article, opts.get_delete_permission())) delete_user.user_permissions.add(get_perm(Section, Section._meta.get_delete_permission())) # login POST dicts self.super_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', LOGIN_FORM_KEY: 1, 'username': 'super', 'password': 'secret', } self.super_email_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', LOGIN_FORM_KEY: 1, 'username': 'super@example.com', 'password': 'secret', } self.super_email_bad_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', LOGIN_FORM_KEY: 1, 'username': 'super@example.com', 'password': 'notsecret', } self.adduser_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', LOGIN_FORM_KEY: 1, 'username': 'adduser', 'password': 'secret', } self.changeuser_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', LOGIN_FORM_KEY: 1, 'username': 'changeuser', 'password': 'secret', } self.deleteuser_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', LOGIN_FORM_KEY: 1, 'username': 'deleteuser', 'password': 'secret', } self.joepublic_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', LOGIN_FORM_KEY: 1, 'username': 'joepublic', 'password': 'secret', } self.no_username_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', LOGIN_FORM_KEY: 1, 'password': 'secret', } def testLogin(self): """ Make sure only staff members can log in. Successful posts to the login page will redirect to the orignal url. Unsuccessfull attempts will continue to render the login page with a 200 status code. """ # Super User response = self.client.get('/test_admin/admin/') self.assertEqual(response.status_code, 200) login = self.client.post('/test_admin/admin/', self.super_login) self.assertRedirects(login, '/test_admin/admin/') self.assertFalse(login.context) self.client.get('/test_admin/admin/logout/') # Test if user enters email address response = self.client.get('/test_admin/admin/') self.assertEqual(response.status_code, 200) login = self.client.post('/test_admin/admin/', self.super_email_login) self.assertContains(login, ERROR_MESSAGE) # only correct passwords get a username hint login = self.client.post('/test_admin/admin/', self.super_email_bad_login) self.assertContains(login, ERROR_MESSAGE) new_user = User(username='jondoe', password='secret', email='super@example.com') new_user.save() # check to ensure if there are multiple email addresses a user doesn't get a 500 login = self.client.post('/test_admin/admin/', self.super_email_login) self.assertContains(login, ERROR_MESSAGE) # Add User response = self.client.get('/test_admin/admin/') self.assertEqual(response.status_code, 200) login = self.client.post('/test_admin/admin/', self.adduser_login) self.assertRedirects(login, '/test_admin/admin/') self.assertFalse(login.context) self.client.get('/test_admin/admin/logout/') # Change User response = self.client.get('/test_admin/admin/') self.assertEqual(response.status_code, 200) login = self.client.post('/test_admin/admin/', self.changeuser_login) self.assertRedirects(login, '/test_admin/admin/') self.assertFalse(login.context) self.client.get('/test_admin/admin/logout/') # Delete User response = self.client.get('/test_admin/admin/') self.assertEqual(response.status_code, 200) login = self.client.post('/test_admin/admin/', self.deleteuser_login) self.assertRedirects(login, '/test_admin/admin/') self.assertFalse(login.context) self.client.get('/test_admin/admin/logout/') # Regular User should not be able to login. response = self.client.get('/test_admin/admin/') self.assertEqual(response.status_code, 200) login = self.client.post('/test_admin/admin/', self.joepublic_login) self.assertEqual(login.status_code, 200) self.assertContains(login, ERROR_MESSAGE) # Requests without username should not return 500 errors. response = self.client.get('/test_admin/admin/') self.assertEqual(response.status_code, 200) login = self.client.post('/test_admin/admin/', self.no_username_login) self.assertEqual(login.status_code, 200) form = login.context[0].get('form') self.assertEqual(form.errors['username'][0], 'This field is required.') def testLoginSuccessfullyRedirectsToOriginalUrl(self): response = self.client.get('/test_admin/admin/') self.assertEqual(response.status_code, 200) query_string = 'the-answer=42' redirect_url = '/test_admin/admin/?%s' % query_string new_next = {REDIRECT_FIELD_NAME: redirect_url} login = self.client.post('/test_admin/admin/', dict(self.super_login, **new_next), QUERY_STRING=query_string) self.assertRedirects(login, redirect_url) def testDoubleLoginIsNotAllowed(self): """Regression test for #19327""" response = self.client.get('/test_admin/admin/') self.assertEqual(response.status_code, 200) # Establish a valid admin session login = self.client.post('/test_admin/admin/', self.super_login) self.assertRedirects(login, '/test_admin/admin/') self.assertFalse(login.context) # Logging in with non-admin user fails login = self.client.post('/test_admin/admin/', self.joepublic_login) self.assertEqual(login.status_code, 200) self.assertContains(login, ERROR_MESSAGE) # Establish a valid admin session login = self.client.post('/test_admin/admin/', self.super_login) self.assertRedirects(login, '/test_admin/admin/') self.assertFalse(login.context) # Logging in with admin user while already logged in login = self.client.post('/test_admin/admin/', self.super_login) self.assertRedirects(login, '/test_admin/admin/') self.assertFalse(login.context) self.client.get('/test_admin/admin/logout/') def testAddView(self): """Test add view restricts access and actually adds items.""" add_dict = {'title': 'Døm ikke', 'content': '

great article

', 'date_0': '2008-03-18', 'date_1': '10:54:39', 'section': 1} # Change User should not have access to add articles self.client.get('/test_admin/admin/') self.client.post('/test_admin/admin/', self.changeuser_login) # make sure the view removes test cookie self.assertEqual(self.client.session.test_cookie_worked(), False) response = self.client.get('/test_admin/admin/admin_views/article/add/') self.assertEqual(response.status_code, 403) # Try POST just to make sure post = self.client.post('/test_admin/admin/admin_views/article/add/', add_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.all().count(), 3) self.client.get('/test_admin/admin/logout/') # Add user may login and POST to add view, then redirect to admin root self.client.get('/test_admin/admin/') self.client.post('/test_admin/admin/', self.adduser_login) addpage = self.client.get('/test_admin/admin/admin_views/article/add/') change_list_link = '› Articles' self.assertNotContains(addpage, change_list_link, msg_prefix='User restricted to add permission is given link to change list view in breadcrumbs.') post = self.client.post('/test_admin/admin/admin_views/article/add/', add_dict) self.assertRedirects(post, '/test_admin/admin/') self.assertEqual(Article.objects.all().count(), 4) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Greetings from a created object') self.client.get('/test_admin/admin/logout/') # Super can add too, but is redirected to the change list view self.client.get('/test_admin/admin/') self.client.post('/test_admin/admin/', self.super_login) addpage = self.client.get('/test_admin/admin/admin_views/article/add/') self.assertContains(addpage, change_list_link, msg_prefix='Unrestricted user is not given link to change list view in breadcrumbs.') post = self.client.post('/test_admin/admin/admin_views/article/add/', add_dict) self.assertRedirects(post, '/test_admin/admin/admin_views/article/') self.assertEqual(Article.objects.all().count(), 5) self.client.get('/test_admin/admin/logout/') # 8509 - if a normal user is already logged in, it is possible # to change user into the superuser without error login = self.client.login(username='joepublic', password='secret') # Check and make sure that if user expires, data still persists self.client.get('/test_admin/admin/') self.client.post('/test_admin/admin/', self.super_login) # make sure the view removes test cookie self.assertEqual(self.client.session.test_cookie_worked(), False) def testChangeView(self): """Change view should restrict access and allow users to edit items.""" change_dict = {'title': 'Ikke fordømt', 'content': '

edited article

', 'date_0': '2008-03-18', 'date_1': '10:54:39', 'section': 1} # add user shoud not be able to view the list of article or change any of them self.client.get('/test_admin/admin/') self.client.post('/test_admin/admin/', self.adduser_login) response = self.client.get('/test_admin/admin/admin_views/article/') self.assertEqual(response.status_code, 403) response = self.client.get('/test_admin/admin/admin_views/article/1/') self.assertEqual(response.status_code, 403) post = self.client.post('/test_admin/admin/admin_views/article/1/', change_dict) self.assertEqual(post.status_code, 403) self.client.get('/test_admin/admin/logout/') # change user can view all items and edit them self.client.get('/test_admin/admin/') self.client.post('/test_admin/admin/', self.changeuser_login) response = self.client.get('/test_admin/admin/admin_views/article/') self.assertEqual(response.status_code, 200) response = self.client.get('/test_admin/admin/admin_views/article/1/') self.assertEqual(response.status_code, 200) post = self.client.post('/test_admin/admin/admin_views/article/1/', change_dict) self.assertRedirects(post, '/test_admin/admin/admin_views/article/') self.assertEqual(Article.objects.get(pk=1).content, '

edited article

') # one error in form should produce singular error message, multiple errors plural change_dict['title'] = '' post = self.client.post('/test_admin/admin/admin_views/article/1/', change_dict) self.assertContains(post, 'Please correct the error below.', msg_prefix='Singular error message not found in response to post with one error') change_dict['content'] = '' post = self.client.post('/test_admin/admin/admin_views/article/1/', change_dict) self.assertContains(post, 'Please correct the errors below.', msg_prefix='Plural error message not found in response to post with multiple errors') self.client.get('/test_admin/admin/logout/') # Test redirection when using row-level change permissions. Refs #11513. RowLevelChangePermissionModel.objects.create(id=1, name="odd id") RowLevelChangePermissionModel.objects.create(id=2, name="even id") for login_dict in [self.super_login, self.changeuser_login, self.adduser_login, self.deleteuser_login]: self.client.post('/test_admin/admin/', login_dict) response = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/1/') self.assertEqual(response.status_code, 403) response = self.client.post('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/1/', {'name': 'changed'}) self.assertEqual(RowLevelChangePermissionModel.objects.get(id=1).name, 'odd id') self.assertEqual(response.status_code, 403) response = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/2/') self.assertEqual(response.status_code, 200) response = self.client.post('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/2/', {'name': 'changed'}) self.assertEqual(RowLevelChangePermissionModel.objects.get(id=2).name, 'changed') self.assertRedirects(response, '/test_admin/admin/') self.client.get('/test_admin/admin/logout/') for login_dict in [self.joepublic_login, self.no_username_login]: self.client.post('/test_admin/admin/', login_dict) response = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/1/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'login-form') response = self.client.post('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/1/', {'name': 'changed'}) self.assertEqual(RowLevelChangePermissionModel.objects.get(id=1).name, 'odd id') self.assertEqual(response.status_code, 200) self.assertContains(response, 'login-form') response = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/2/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'login-form') response = self.client.post('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/2/', {'name': 'changed again'}) self.assertEqual(RowLevelChangePermissionModel.objects.get(id=2).name, 'changed') self.assertEqual(response.status_code, 200) self.assertContains(response, 'login-form') self.client.get('/test_admin/admin/logout/') def testHistoryView(self): """History view should restrict access.""" # add user shoud not be able to view the list of article or change any of them self.client.get('/test_admin/admin/') self.client.post('/test_admin/admin/', self.adduser_login) response = self.client.get('/test_admin/admin/admin_views/article/1/history/') self.assertEqual(response.status_code, 403) self.client.get('/test_admin/admin/logout/') # change user can view all items and edit them self.client.get('/test_admin/admin/') self.client.post('/test_admin/admin/', self.changeuser_login) response = self.client.get('/test_admin/admin/admin_views/article/1/history/') self.assertEqual(response.status_code, 200) # Test redirection when using row-level change permissions. Refs #11513. RowLevelChangePermissionModel.objects.create(id=1, name="odd id") RowLevelChangePermissionModel.objects.create(id=2, name="even id") for login_dict in [self.super_login, self.changeuser_login, self.adduser_login, self.deleteuser_login]: self.client.post('/test_admin/admin/', login_dict) response = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/1/history/') self.assertEqual(response.status_code, 403) response = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/2/history/') self.assertEqual(response.status_code, 200) self.client.get('/test_admin/admin/logout/') for login_dict in [self.joepublic_login, self.no_username_login]: self.client.post('/test_admin/admin/', login_dict) response = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/1/history/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'login-form') response = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/2/history/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'login-form') self.client.get('/test_admin/admin/logout/') def testConditionallyShowAddSectionLink(self): """ The foreign key widget should only show the "add related" button if the user has permission to add that related item. """ # Set up and log in user. url = '/test_admin/admin/admin_views/article/add/' add_link_text = ' class="add-another"' self.client.get('/test_admin/admin/') self.client.post('/test_admin/admin/', self.adduser_login) # The add user can't add sections yet, so they shouldn't see the "add # section" link. response = self.client.get(url) self.assertNotContains(response, add_link_text) # Allow the add user to add sections too. Now they can see the "add # section" link. add_user = User.objects.get(username='adduser') perm = get_perm(Section, Section._meta.get_add_permission()) add_user.user_permissions.add(perm) response = self.client.get(url) self.assertContains(response, add_link_text) def testCustomModelAdminTemplates(self): self.client.get('/test_admin/admin/') self.client.post('/test_admin/admin/', self.super_login) # Test custom change list template with custom extra context response = self.client.get('/test_admin/admin/admin_views/customarticle/') self.assertContains(response, "var hello = 'Hello!';") self.assertTemplateUsed(response, 'custom_admin/change_list.html') # Test custom add form template response = self.client.get('/test_admin/admin/admin_views/customarticle/add/') self.assertTemplateUsed(response, 'custom_admin/add_form.html') # Add an article so we can test delete, change, and history views post = self.client.post('/test_admin/admin/admin_views/customarticle/add/', { 'content': '

great article

', 'date_0': '2008-03-18', 'date_1': '10:54:39' }) self.assertRedirects(post, '/test_admin/admin/admin_views/customarticle/') self.assertEqual(CustomArticle.objects.all().count(), 1) article_pk = CustomArticle.objects.all()[0].pk # Test custom delete, change, and object history templates # Test custom change form template response = self.client.get('/test_admin/admin/admin_views/customarticle/%d/' % article_pk) self.assertTemplateUsed(response, 'custom_admin/change_form.html') response = self.client.get('/test_admin/admin/admin_views/customarticle/%d/delete/' % article_pk) self.assertTemplateUsed(response, 'custom_admin/delete_confirmation.html') response = self.client.post('/test_admin/admin/admin_views/customarticle/', data={ 'index': 0, 'action': ['delete_selected'], '_selected_action': ['1'], }) self.assertTemplateUsed(response, 'custom_admin/delete_selected_confirmation.html') response = self.client.get('/test_admin/admin/admin_views/customarticle/%d/history/' % article_pk) self.assertTemplateUsed(response, 'custom_admin/object_history.html') self.client.get('/test_admin/admin/logout/') def testDeleteView(self): """Delete view should restrict access and actually delete items.""" delete_dict = {'post': 'yes'} # add user shoud not be able to delete articles self.client.get('/test_admin/admin/') self.client.post('/test_admin/admin/', self.adduser_login) response = self.client.get('/test_admin/admin/admin_views/article/1/delete/') self.assertEqual(response.status_code, 403) post = self.client.post('/test_admin/admin/admin_views/article/1/delete/', delete_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.all().count(), 3) self.client.get('/test_admin/admin/logout/') # Delete user can delete self.client.get('/test_admin/admin/') self.client.post('/test_admin/admin/', self.deleteuser_login) response = self.client.get('/test_admin/admin/admin_views/section/1/delete/') # test response contains link to related Article self.assertContains(response, "admin_views/article/1/") response = self.client.get('/test_admin/admin/admin_views/article/1/delete/') self.assertEqual(response.status_code, 200) post = self.client.post('/test_admin/admin/admin_views/article/1/delete/', delete_dict) self.assertRedirects(post, '/test_admin/admin/') self.assertEqual(Article.objects.all().count(), 2) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Greetings from a deleted object') article_ct = ContentType.objects.get_for_model(Article) logged = LogEntry.objects.get(content_type=article_ct, action_flag=DELETION) self.assertEqual(logged.object_id, '1') self.client.get('/test_admin/admin/logout/') def testDisabledPermissionsWhenLoggedIn(self): self.client.login(username='super', password='secret') superuser = User.objects.get(username='super') superuser.is_active = False superuser.save() response = self.client.get('/test_admin/admin/') self.assertContains(response, 'id="login-form"') self.assertNotContains(response, 'Log out') response = self.client.get('/test_admin/admin/secure-view/') self.assertContains(response, 'id="login-form"') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminViewsNoUrlTest(TestCase): """Regression test for #17333""" urls = "admin_views.urls" fixtures = ['admin-views-users.xml'] def setUp(self): opts = Report._meta # User who can change Reports change_user = User.objects.get(username='changeuser') change_user.user_permissions.add(get_perm(Report, opts.get_change_permission())) # login POST dict self.changeuser_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', LOGIN_FORM_KEY: 1, 'username': 'changeuser', 'password': 'secret', } def test_no_standard_modeladmin_urls(self): """Admin index views don't break when user's ModelAdmin removes standard urls""" self.client.get('/test_admin/admin/') self.client.post('/test_admin/admin/', self.changeuser_login) r = self.client.get('/test_admin/admin/') # we shouldn' get an 500 error caused by a NoReverseMatch self.assertEqual(r.status_code, 200) self.client.get('/test_admin/admin/logout/') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class AdminViewDeletedObjectsTest(TestCase): urls = "admin_views.urls" fixtures = ['admin-views-users.xml', 'deleted-objects.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_nesting(self): """ Objects should be nested to display the relationships that cause them to be scheduled for deletion. """ pattern = re.compile(br"""
  • Plot: World Domination\s*