# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import re import datetime import unittest from django.conf import settings, global_settings from django.core import mail from django.core.checks import Error from django.core.files import temp as tempfile from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import (NoReverseMatch, get_script_prefix, reverse, set_script_prefix) # Register auth models with the admin. from django.contrib.auth import get_permission_codename from django.contrib.admin import ModelAdmin from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.models import LogEntry, DELETION from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.templatetags.admin_static import static from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase from django.contrib.admin.utils import quote from django.contrib.admin.validation import ModelAdminValidator from django.contrib.admin.views.main import IS_POPUP_VAR 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.contrib.staticfiles.storage import staticfiles_storage from django.forms.utils import ErrorList from django.template.response import TemplateResponse from django.test import TestCase, skipUnlessDBFeature from django.test.utils import patch_logger from django.test import modify_settings, override_settings from django.utils import formats from django.utils import translation from django.utils.cache import get_max_age from django.utils.encoding import iri_to_uri, force_bytes, force_text from django.utils.html import escape from django.utils.http import urlencode from django.utils.six.moves.urllib.parse import parse_qsl, urljoin, urlparse from django.utils._os import upath from django.utils import six # 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, UnchangeableObject, Choice, ShortMessage, Telegram, Pizza, Topping, FilteredManager, City, Restaurant, Worker, ParentWithDependentChildren, Character, FieldOverridePost, Color2) from .admin import site, site2, CityAdmin ERROR_MESSAGE = "Please enter the correct username and password \ for a staff account. Note that both fields may be case-sensitive." ADMIN_VIEW_TEMPLATES_DIR = settings.TEMPLATE_DIRS + (os.path.join(os.path.dirname(upath(__file__)), 'templates'),) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls", USE_I18N=True, USE_L10N=False, LANGUAGE_CODE='en') class AdminViewBasicTestCase(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' def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): 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) class AdminViewBasicTest(AdminViewBasicTestCase): def test_trailing_slash_required(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 test_admin_static_template_tag(self): """ Test that admin_static.static is pointing to the collectstatic version (as django.contrib.collectstatic is in installed apps). """ old_url = staticfiles_storage.base_url staticfiles_storage.base_url = '/test/' try: self.assertEqual(static('path'), '/test/path') finally: staticfiles_storage.base_url = old_url def test_basic_add_GET(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 test_add_with_GET_args(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 test_basic_edit_GET(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 test_basic_edit_GET_string_PK(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 test_basic_inheritance_GET_string_PK(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 test_basic_add_POST(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 test_popup_add_POST(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 test_basic_edit_POST(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 test_edit_save_as(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 test_change_list_sorting_callable(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 test_change_list_sorting_model(self): """ Ensure we can sort on a list_display field that is a Model method (column 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 test_change_list_sorting_model_admin(self): """ Ensure we can sort on a list_display field that is a ModelAdmin method (column 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 test_change_list_sorting_model_admin_reverse(self): """ Ensure we can sort on a list_display field that is a ModelAdmin method in reverse order (i.e. admin_order_field uses the '-' prefix) (column 6 is 'model_year_reverse' in ArticleAdmin) """ response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit, {'o': '6'}) self.assertContentBefore(response, '2009', '2008', "Results of sorting on ModelAdmin method are out of order.") self.assertContentBefore(response, '2008', '2000', "Results of sorting on ModelAdmin method are out of order.") # Let's make sure the ordering is right and that we don't get a # FieldError when we change to descending order response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit, {'o': '-6'}) self.assertContentBefore(response, '2000', '2008', "Results of sorting on ModelAdmin method are out of order.") self.assertContentBefore(response, '2008', '2009', "Results of sorting on ModelAdmin method are out of order.") def test_change_list_sorting_multiple(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 test_change_list_sorting_preserve_queryset_ordering(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 test_change_list_sorting_model_meta(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 test_change_list_sorting_override_model_admin(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 test_multiple_sort_same_field(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 test_relation_spanning_filters(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 test_incorrect_lookup_parameters(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 test_isnull_lookups(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 test_logout_and_password_change_URLs(self): response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit) self.assertContains(response, '' % self.urlbit) self.assertContains(response, '' % self.urlbit) def test_named_group_field_choices_change_list(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 test_named_group_field_choices_filter(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 test_change_list_null_boolean_display(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 test_i18n_language_non_english_default(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'), translation.override('en-us'): response = self.client.get('/test_admin/admin/jsi18n/') self.assertNotContains(response, 'Choisir une heure') def test_i18n_language_non_english_fallback(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'), translation.override('none'): response = self.client.get('/test_admin/admin/jsi18n/') self.assertContains(response, 'Choisir une heure') def test_L10N_deactivated(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), 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_disallowed_to_field(self): with patch_logger('django.security.DisallowedModelAdminToField', 'error') as calls: response = self.client.get("/test_admin/admin/admin_views/section/", {TO_FIELD_VAR: 'missing_field'}) self.assertEqual(response.status_code, 400) self.assertEqual(len(calls), 1) # Specifying a field that is not refered by any other model registered # to this admin site should raise an exception. with patch_logger('django.security.DisallowedModelAdminToField', 'error') as calls: response = self.client.get("/test_admin/admin/admin_views/section/", {TO_FIELD_VAR: 'name'}) self.assertEqual(response.status_code, 400) self.assertEqual(len(calls), 1) # Specifying a field referenced by another model should be allowed. response = self.client.get("/test_admin/admin/admin_views/section/", {TO_FIELD_VAR: 'id'}) self.assertEqual(response.status_code, 200) # Specifying a field referenced by another model though a m2m should be allowed. response = self.client.get("/test_admin/admin/admin_views/m2mreference/", {TO_FIELD_VAR: 'id'}) self.assertEqual(response.status_code, 200) # Specifying a field that is not refered by any other model directly registered # to this admin site but registered through inheritance should be allowed. response = self.client.get("/test_admin/admin/admin_views/referencedbyparent/", {TO_FIELD_VAR: 'id'}) self.assertEqual(response.status_code, 200) # We also want to prevent the add and change view from leaking a # disallowed field value. with patch_logger('django.security.DisallowedModelAdminToField', 'error') as calls: response = self.client.post("/test_admin/admin/admin_views/section/add/", {TO_FIELD_VAR: 'name'}) self.assertEqual(response.status_code, 400) self.assertEqual(len(calls), 1) section = Section.objects.create() with patch_logger('django.security.DisallowedModelAdminToField', 'error') as calls: response = self.client.post("/test_admin/admin/admin_views/section/%d/" % section.pk, {TO_FIELD_VAR: 'name'}) self.assertEqual(response.status_code, 400) self.assertEqual(len(calls), 1) 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_popup_dismiss_related(self): """ Regression test for ticket 20664 - ensure the pk is properly quoted. """ actor = Actor.objects.create(name="Palin", age=27) response = self.client.get("/test_admin/admin/admin_views/actor/?%s" % IS_POPUP_VAR) self.assertContains(response, "opener.dismissRelatedLookupPopup(window, '%s')" % actor.pk) 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') 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) def test_changelist_with_no_change_url(self): """ ModelAdmin.changelist_view shouldn't result in a NoReverseMatch if url for change_view is removed from get_urls Regression test for #20934 """ UnchangeableObject.objects.create() response = self.client.get('/test_admin/admin/admin_views/unchangeableobject/') self.assertEqual(response.status_code, 200) # Check the format of the shown object -- shouldn't contain a change link self.assertContains(response, 'UnchangeableObject object', html=True) def test_invalid_appindex_url(self): """ #21056 -- URL reversing shouldn't work for nonexistent apps. """ good_url = '/test_admin/admin/admin_views/' confirm_good_url = reverse('admin:app_list', kwargs={'app_label': 'admin_views'}) self.assertEqual(good_url, confirm_good_url) with self.assertRaises(NoReverseMatch): reverse('admin:app_list', kwargs={'app_label': 'this_should_fail'}) with self.assertRaises(NoReverseMatch): reverse('admin:app_list', args=('admin_views2',)) def test_proxy_model_content_type_is_used_for_log_entries(self): """ Log entries for proxy models should have the proxy model's content type. Regression test for #21084. """ color2_content_type = ContentType.objects.get_for_model(Color2, for_concrete_model=False) # add color2_add_url = reverse('admin:admin_views_color2_add') self.client.post(color2_add_url, {'value': 'orange'}) color2_addition_log = LogEntry.objects.all()[0] self.assertEqual(color2_content_type, color2_addition_log.content_type) # change color_id = color2_addition_log.object_id color2_change_url = reverse('admin:admin_views_color2_change', args=(color_id,)) self.client.post(color2_change_url, {'value': 'blue'}) color2_change_log = LogEntry.objects.all()[0] self.assertEqual(color2_content_type, color2_change_log.content_type) # delete color2_delete_url = reverse('admin:admin_views_color2_delete', args=(color_id,)) self.client.post(color2_delete_url) color2_delete_log = LogEntry.objects.all()[0] self.assertEqual(color2_content_type, color2_delete_log.content_type) def test_adminsite_display_site_url(self): """ #13749 - Admin should display link to front-end site 'View site' """ url = reverse('admin:index') response = self.client.get(url) self.assertEqual(response.context['site_url'], '/my-site-url/') self.assertContains(response, 'View site') @override_settings(TEMPLATE_DIRS=ADMIN_VIEW_TEMPLATES_DIR) class AdminCustomTemplateTests(AdminViewBasicTestCase): def test_extended_bodyclass_template_change_form(self): """ Ensure that the admin/change_form.html template uses block.super in the bodyclass block. """ response = self.client.get('/test_admin/%s/admin_views/section/add/' % self.urlbit) self.assertContains(response, 'bodyclass_consistency_check ') def test_extended_bodyclass_template_change_password(self): """ Ensure that the auth/user/change_password.html template uses block super in the bodyclass block. """ user = User.objects.get(username='super') response = self.client.get('/test_admin/%s/auth/user/%s/password/' % (self.urlbit, user.id)) self.assertContains(response, 'bodyclass_consistency_check ') def test_extended_bodyclass_template_index(self): """ Ensure that the admin/index.html template uses block.super in the bodyclass block. """ response = self.client.get('/test_admin/%s/' % self.urlbit) self.assertContains(response, 'bodyclass_consistency_check ') def test_extended_bodyclass_change_list(self): """ Ensure that the admin/change_list.html' template uses block.super in the bodyclass block. """ response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit) self.assertContains(response, 'bodyclass_consistency_check ') def test_extended_bodyclass_template_login(self): """ Ensure that the admin/login.html template uses block.super in the bodyclass block. """ self.client.logout() response = self.client.get('/test_admin/%s/login/' % self.urlbit) self.assertContains(response, 'bodyclass_consistency_check ') def test_extended_bodyclass_template_delete_confirmation(self): """ Ensure that the admin/delete_confirmation.html template uses block.super in the bodyclass block. """ group = Group.objects.create(name="foogroup") response = self.client.get('/test_admin/%s/auth/group/%s/delete/' % (self.urlbit, group.id)) self.assertContains(response, 'bodyclass_consistency_check ') def test_extended_bodyclass_template_delete_selected_confirmation(self): """ Ensure that the admin/delete_selected_confirmation.html template uses block.super in bodyclass block. """ group = Group.objects.create(name="foogroup") post_data = { 'action': 'delete_selected', 'selected_across': '0', 'index': '0', '_selected_action': group.id } response = self.client.post('/test_admin/%s/auth/group/' % (self.urlbit), post_data) self.assertContains(response, 'bodyclass_consistency_check ') def test_filter_with_custom_template(self): """ Ensure that one can use a custom template to render an admin filter. Refs #17515. """ 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',), ROOT_URLCONF="admin_views.urls") class AdminViewFormUrlTest(TestCase): fixtures = ["admin-views-users.xml"] urlbit = "admin3" def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_change_form_URL_has_correct_value(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_initial_data_can_be_overridden(self): """ Tests that the behavior for setting initial form data can be overridden in the ModelAdmin class. Usually, the initial value is set via the GET params. """ response = self.client.get('/test_admin/%s/admin_views/restaurant/add/' % self.urlbit, {'name': 'test_value'}) # this would be the usual behaviour self.assertNotContains(response, 'value="test_value"') # this is the overridden behaviour self.assertContains(response, 'value="overridden_value"') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class AdminJavaScriptTest(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() 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',), ROOT_URLCONF="admin_views.urls") class SaveAsTests(TestCase): 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} 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/') @override_settings(ROOT_URLCONF="admin_views.urls") class CustomModelAdminTest(AdminViewBasicTestCase): urlbit = "admin2" def test_custom_admin_site_login_form(self): self.client.logout() response = self.client.get('/test_admin/admin2/', follow=True) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) login = self.client.post('/test_admin/admin2/login/', { REDIRECT_FIELD_NAME: '/test_admin/admin2/', 'username': 'customform', 'password': 'secret', }, follow=True) self.assertIsInstance(login, TemplateResponse) self.assertEqual(login.status_code, 200) self.assertContains(login, 'custom form error') def test_custom_admin_site_login_template(self): self.client.logout() response = self.client.get('/test_admin/admin2/', follow=True) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, 'custom_admin/login.html') self.assertContains(response, 'Hello from a custom login template') def test_custom_admin_site_logout_template(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 test_custom_admin_site_index_view_and_template(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 test_custom_admin_site_app_index_view_and_template(self): response = self.client.get('/test_admin/admin2/admin_views/') self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, 'custom_admin/app_index.html') self.assertContains(response, 'Hello from a custom app_index template') def test_custom_admin_site_password_change_template(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 test_custom_admin_site_password_change_done_template(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 test_custom_admin_site_view(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',), ROOT_URLCONF="admin_views.urls") class AdminViewPermissionsTest(TestCase): """Tests for Admin Views Permissions.""" 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, get_permission_codename('add', opts))) # User who can change Articles change_user = User.objects.get(username='changeuser') change_user.user_permissions.add(get_perm(Article, get_permission_codename('change', opts))) # User who can delete Articles delete_user = User.objects.get(username='deleteuser') delete_user.user_permissions.add(get_perm(Article, get_permission_codename('delete', opts))) delete_user.user_permissions.add(get_perm(Section, get_permission_codename('delete', Section._meta))) # login POST dicts self.super_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', 'username': 'super', 'password': 'secret', } self.super_email_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', 'username': 'super@example.com', 'password': 'secret', } self.super_email_bad_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', 'username': 'super@example.com', 'password': 'notsecret', } self.adduser_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', 'username': 'adduser', 'password': 'secret', } self.changeuser_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', 'username': 'changeuser', 'password': 'secret', } self.deleteuser_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', 'username': 'deleteuser', 'password': 'secret', } self.joepublic_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', 'username': 'joepublic', 'password': 'secret', } self.no_username_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', 'password': 'secret', } def test_login(self): """ Make sure only staff members can log in. Successful posts to the login page will redirect to the original url. Unsuccessful attempts will continue to render the login page with a 200 status code. """ login_url = reverse('admin:login') + '?next=/test_admin/admin/' # Super User response = self.client.get('/test_admin/admin/') self.assertEqual(response.status_code, 302) login = self.client.post(login_url, 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, 302) login = self.client.post(login_url, self.super_email_login) self.assertContains(login, ERROR_MESSAGE) # only correct passwords get a username hint login = self.client.post(login_url, 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(login_url, self.super_email_login) self.assertContains(login, ERROR_MESSAGE) # Add User response = self.client.get('/test_admin/admin/') self.assertEqual(response.status_code, 302) login = self.client.post(login_url, 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, 302) login = self.client.post(login_url, 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, 302) login = self.client.post(login_url, 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, 302) login = self.client.post(login_url, 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, 302) login = self.client.post(login_url, 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 test_login_successfully_redirects_to_original_URL(self): response = self.client.get('/test_admin/admin/') self.assertEqual(response.status_code, 302) query_string = 'the-answer=42' redirect_url = '/test_admin/admin/?%s' % query_string new_next = {REDIRECT_FIELD_NAME: redirect_url} post_data = self.super_login.copy() post_data.pop(REDIRECT_FIELD_NAME) login = self.client.post( '%s?%s' % (reverse('admin:login'), urlencode(new_next)), post_data) self.assertRedirects(login, redirect_url) def test_double_login_is_not_allowed(self): """Regression test for #19327""" login_url = reverse('admin:login') + '?next=/test_admin/admin/' response = self.client.get('/test_admin/admin/') self.assertEqual(response.status_code, 302) # Establish a valid admin session login = self.client.post(login_url, self.super_login) self.assertRedirects(login, '/test_admin/admin/') self.assertFalse(login.context) # Logging in with non-admin user fails login = self.client.post(login_url, self.joepublic_login) self.assertEqual(login.status_code, 200) self.assertContains(login, ERROR_MESSAGE) # Establish a valid admin session login = self.client.post(login_url, 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(login_url, self.super_login) self.assertRedirects(login, '/test_admin/admin/') self.assertFalse(login.context) self.client.get('/test_admin/admin/logout/') def test_add_view(self): """Test add view restricts access and actually adds items.""" login_url = reverse('admin:login') + '?next=/test_admin/admin/' 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(login_url, 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(login_url, 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(login_url, 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 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(login_url, self.super_login) # make sure the view removes test cookie self.assertEqual(self.client.session.test_cookie_worked(), False) def test_change_view(self): """Change view should restrict access and allow users to edit items.""" login_url = reverse('admin:login') + '?next=/test_admin/admin/' change_dict = {'title': 'Ikke fordømt', 'content': '

edited article

', 'date_0': '2008-03-18', 'date_1': '10:54:39', 'section': 1} # add user should not be able to view the list of article or change any of them self.client.get('/test_admin/admin/') self.client.post(login_url, 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(login_url, 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(login_url, 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(login_url, login_dict) response = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/1/', follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, 'login-form') response = self.client.post('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/1/', {'name': 'changed'}, follow=True) 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/', follow=True) 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'}, follow=True) 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 test_history_view(self): """History view should restrict access.""" login_url = reverse('admin:login') + '?next=/test_admin/admin/' # add user should not be able to view the list of article or change any of them self.client.get('/test_admin/admin/') self.client.post(login_url, 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(login_url, 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(login_url, 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(login_url, login_dict) response = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/1/history/', follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, 'login-form') response = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/2/history/', follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, 'login-form') self.client.get('/test_admin/admin/logout/') def test_conditionally_show_add_section_link(self): """ The foreign key widget should only show the "add related" button if the user has permission to add that related item. """ login_url = reverse('admin:login') + '?next=/test_admin/admin/' # 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(login_url, 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, get_permission_codename('add', Section._meta)) add_user.user_permissions.add(perm) response = self.client.get(url) self.assertContains(response, add_link_text) def test_custom_model_admin_templates(self): login_url = reverse('admin:login') + '?next=/test_admin/admin/' self.client.get('/test_admin/admin/') self.client.post(login_url, 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 test_delete_view(self): """Delete view should restrict access and actually delete items.""" login_url = reverse('admin:login') + '?next=/test_admin/admin/' delete_dict = {'post': 'yes'} # add user should not be able to delete articles self.client.get('/test_admin/admin/') self.client.post(login_url, 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(login_url, self.deleteuser_login) response = self.client.get('/test_admin/admin/admin_views/section/1/delete/') self.assertContains(response, "

Summary

") self.assertContains(response, "
  • Articles: 3
  • ") # 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.assertContains(response, "admin_views/article/1/") self.assertContains(response, "

    Summary

    ") self.assertContains(response, "
  • Articles: 1
  • ") 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 test_disabled_permissions_when_logged_in(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/', follow=True) self.assertContains(response, 'id="login-form"') self.assertNotContains(response, 'Log out') response = self.client.get('/test_admin/admin/secure-view/', follow=True) self.assertContains(response, 'id="login-form"') def test_disabled_staff_permissions_when_logged_in(self): self.client.login(username='super', password='secret') superuser = User.objects.get(username='super') superuser.is_staff = False superuser.save() response = self.client.get('/test_admin/admin/', follow=True) self.assertContains(response, 'id="login-form"') self.assertNotContains(response, 'Log out') response = self.client.get('/test_admin/admin/secure-view/', follow=True) self.assertContains(response, 'id="login-form"') def test_app_index_fail_early(self): """ If a user has no module perms, avoid iterating over all the modeladmins in the registry. """ login_url = reverse('admin:login') + '?next=/test_admin/admin/' opts = Article._meta change_user = User.objects.get(username='changeuser') permission = get_perm(Article, get_permission_codename('change', opts)) self.client.post(login_url, self.changeuser_login) # the user has no module permissions, because this module doesn't exist change_user.user_permissions.remove(permission) response = self.client.get('/test_admin/admin/admin_views/') self.assertEqual(response.status_code, 403) # the user now has module permissions change_user.user_permissions.add(permission) response = self.client.get('/test_admin/admin/admin_views/') self.assertEqual(response.status_code, 200) def test_shortcut_view_only_available_to_staff(self): """ Only admin users should be able to use the admin shortcut view. """ model_ctype = ContentType.objects.get_for_model(ModelWithStringPrimaryKey) obj = ModelWithStringPrimaryKey.objects.create(string_pk='foo') shortcut_url = "/test_admin/admin/r/%s/%s/" % (model_ctype.pk, obj.pk) # Not logged in: we should see the login page. response = self.client.get(shortcut_url, follow=True) self.assertTemplateUsed(response, 'admin/login.html') # Logged in? Redirect. self.client.login(username='super', password='secret') response = self.client.get(shortcut_url, follow=False) # Can't use self.assertRedirects() because User.get_absolute_url() is silly. self.assertEqual(response.status_code, 302) # Domain may depend on contrib.sites tests also run six.assertRegex(self, response.url, 'http://(testserver|example.com)/dummy/foo/') def test_has_module_permission(self): """ Ensure that has_module_permission() returns True for all users who have any permission for that module (add, change, or delete), so that the module is displayed on the admin index page. """ login_url = reverse('admin:login') + '?next=/test_admin/admin/' self.client.post(login_url, self.super_login) response = self.client.get('/test_admin/admin/') self.assertContains(response, 'admin_views') self.assertContains(response, 'Articles') self.client.get('/test_admin/admin/logout/') self.client.post(login_url, self.adduser_login) response = self.client.get('/test_admin/admin/') self.assertContains(response, 'admin_views') self.assertContains(response, 'Articles') self.client.get('/test_admin/admin/logout/') self.client.post(login_url, self.changeuser_login) response = self.client.get('/test_admin/admin/') self.assertContains(response, 'admin_views') self.assertContains(response, 'Articles') self.client.get('/test_admin/admin/logout/') self.client.post(login_url, self.deleteuser_login) response = self.client.get('/test_admin/admin/') self.assertContains(response, 'admin_views') self.assertContains(response, 'Articles') self.client.get('/test_admin/admin/logout/') def test_overriding_has_module_permission(self): """ Ensure that overriding has_module_permission() has the desired effect. In this case, it always returns False, so the module should not be displayed on the admin index page for any users. """ login_url = reverse('admin:login') + '?next=/test_admin/admin7/' self.client.post(login_url, self.super_login) response = self.client.get('/test_admin/admin7/') self.assertNotContains(response, 'admin_views') self.assertNotContains(response, 'Articles') self.client.get('/test_admin/admin7/logout/') self.client.post(login_url, self.adduser_login) response = self.client.get('/test_admin/admin7/') self.assertNotContains(response, 'admin_views') self.assertNotContains(response, 'Articles') self.client.get('/test_admin/admin7/logout/') self.client.post(login_url, self.changeuser_login) response = self.client.get('/test_admin/admin7/') self.assertNotContains(response, 'admin_views') self.assertNotContains(response, 'Articles') self.client.get('/test_admin/admin7/logout/') self.client.post(login_url, self.deleteuser_login) response = self.client.get('/test_admin/admin7/') self.assertNotContains(response, 'admin_views') self.assertNotContains(response, 'Articles') self.client.get('/test_admin/admin7/logout/') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class AdminViewsNoUrlTest(TestCase): """Regression test for #17333""" 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, get_permission_codename('change', opts))) # login POST dict self.changeuser_login = { REDIRECT_FIELD_NAME: '/test_admin/admin/', '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/') r = self.client.post(reverse('admin:login'), 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/') @skipUnlessDBFeature('can_defer_constraint_checks') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class AdminViewDeletedObjectsTest(TestCase): 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*
      \s*
    • Plot details: almost finished""") response = self.client.get('/test_admin/admin/admin_views/villain/%s/delete/' % quote(1)) six.assertRegex(self, response.content, pattern) def test_cyclic(self): """ Cyclic relationships should still cause each object to only be listed once. """ one = """
    • Cyclic one: I am recursive""" two = """
    • Cyclic two: I am recursive too""" response = self.client.get('/test_admin/admin/admin_views/cyclicone/%s/delete/' % quote(1)) self.assertContains(response, one, 1) self.assertContains(response, two, 1) def test_perms_needed(self): self.client.logout() delete_user = User.objects.get(username='deleteuser') delete_user.user_permissions.add(get_perm(Plot, get_permission_codename('delete', Plot._meta))) self.assertTrue(self.client.login(username='deleteuser', password='secret')) response = self.client.get('/test_admin/admin/admin_views/plot/%s/delete/' % quote(1)) self.assertContains(response, "your account doesn't have permission to delete the following types of objects") self.assertContains(response, "
    • plot details
    • ") def test_protected(self): q = Question.objects.create(question="Why?") a1 = Answer.objects.create(question=q, answer="Because.") a2 = Answer.objects.create(question=q, answer="Yes.") response = self.client.get("/test_admin/admin/admin_views/question/%s/delete/" % quote(q.pk)) self.assertContains(response, "would require deleting the following protected related objects") self.assertContains(response, '
    • Answer: Because.
    • ' % a1.pk) self.assertContains(response, '
    • Answer: Yes.
    • ' % a2.pk) def test_not_registered(self): should_contain = """
    • Secret hideout: underground bunker""" response = self.client.get('/test_admin/admin/admin_views/villain/%s/delete/' % quote(1)) self.assertContains(response, should_contain, 1) def test_multiple_fkeys_to_same_model(self): """ If a deleted object has two relationships from another model, both of those should be followed in looking for related objects to delete. """ should_contain = """
    • Plot: World Domination""" response = self.client.get('/test_admin/admin/admin_views/villain/%s/delete/' % quote(1)) self.assertContains(response, should_contain) response = self.client.get('/test_admin/admin/admin_views/villain/%s/delete/' % quote(2)) self.assertContains(response, should_contain) def test_multiple_fkeys_to_same_instance(self): """ If a deleted object has two relationships pointing to it from another object, the other object should still only be listed once. """ should_contain = """
    • Plot: World Peace
    • """ response = self.client.get('/test_admin/admin/admin_views/villain/%s/delete/' % quote(2)) self.assertContains(response, should_contain, 1) def test_inheritance(self): """ In the case of an inherited model, if either the child or parent-model instance is deleted, both instances are listed for deletion, as well as any relationships they have. """ should_contain = [ """
    • Villain: Bob""", """
    • Super villain: Bob""", """
    • Secret hideout: floating castle""", """
    • Super secret hideout: super floating castle!""" ] response = self.client.get('/test_admin/admin/admin_views/villain/%s/delete/' % quote(3)) for should in should_contain: self.assertContains(response, should, 1) response = self.client.get('/test_admin/admin/admin_views/supervillain/%s/delete/' % quote(3)) for should in should_contain: self.assertContains(response, should, 1) def test_generic_relations(self): """ If a deleted object has GenericForeignKeys pointing to it, those objects should be listed for deletion. """ plot = Plot.objects.get(pk=3) FunkyTag.objects.create(content_object=plot, name='hott') should_contain = """
    • Funky tag: hott""" response = self.client.get('/test_admin/admin/admin_views/plot/%s/delete/' % quote(3)) self.assertContains(response, should_contain) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class TestGenericRelations(TestCase): fixtures = ['admin-views-users.xml', 'deleted-objects.xml'] def setUp(self): self.client.login(username='super', password='secret') def test_generic_content_object_in_list_display(self): plot = Plot.objects.get(pk=3) FunkyTag.objects.create(content_object=plot, name='hott') response = self.client.get('/test_admin/admin/admin_views/funkytag/') self.assertContains(response, "%s" % plot) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class AdminViewStringPrimaryKeyTest(TestCase): fixtures = ['admin-views-users.xml', 'string-primary-key.xml'] def __init__(self, *args): super(AdminViewStringPrimaryKeyTest, self).__init__(*args) self.pk = """abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 -_.!~*'() ;/?:@&=+$, <>#%" {}|\^[]`""" def setUp(self): self.client.login(username='super', password='secret') content_type_pk = ContentType.objects.get_for_model(ModelWithStringPrimaryKey).pk LogEntry.objects.log_action(100, content_type_pk, self.pk, self.pk, 2, change_message='Changed something') def tearDown(self): self.client.logout() def test_get_history_view(self): """ Retrieving the history for an object using urlencoded form of primary key should work. Refs #12349, #18550. """ response = self.client.get('/test_admin/admin/admin_views/modelwithstringprimarykey/%s/history/' % quote(self.pk)) self.assertContains(response, escape(self.pk)) self.assertContains(response, 'Changed something') self.assertEqual(response.status_code, 200) def test_get_change_view(self): "Retrieving the object using urlencoded form of primary key should work" response = self.client.get('/test_admin/admin/admin_views/modelwithstringprimarykey/%s/' % quote(self.pk)) self.assertContains(response, escape(self.pk)) self.assertEqual(response.status_code, 200) def test_changelist_to_changeform_link(self): "Link to the changeform of the object in changelist should use reverse() and be quoted -- #18072" prefix = '/test_admin/admin/admin_views/modelwithstringprimarykey/' response = self.client.get(prefix) # this URL now comes through reverse(), thus url quoting and iri_to_uri encoding pk_final_url = escape(iri_to_uri(quote(self.pk))) should_contain = """%s""" % (prefix, pk_final_url, escape(self.pk)) self.assertContains(response, should_contain) def test_recentactions_link(self): "The link from the recent actions list referring to the changeform of the object should be quoted" response = self.client.get('/test_admin/admin/') link = reverse('admin:admin_views_modelwithstringprimarykey_change', args=(quote(self.pk),)) should_contain = """%s""" % (escape(link), escape(self.pk)) self.assertContains(response, should_contain) def test_recentactions_without_content_type(self): "If a LogEntry is missing content_type it will not display it in span tag under the hyperlink." response = self.client.get('/test_admin/admin/') link = reverse('admin:admin_views_modelwithstringprimarykey_change', args=(quote(self.pk),)) should_contain = """%s""" % (escape(link), escape(self.pk)) self.assertContains(response, should_contain) should_contain = "Model with string primary key" # capitalized in Recent Actions self.assertContains(response, should_contain) logentry = LogEntry.objects.get(content_type__name__iexact=should_contain) # http://code.djangoproject.com/ticket/10275 # if the log entry doesn't have a content type it should still be # possible to view the Recent Actions part logentry.content_type = None logentry.save() counted_presence_before = response.content.count(force_bytes(should_contain)) response = self.client.get('/test_admin/admin/') counted_presence_after = response.content.count(force_bytes(should_contain)) self.assertEqual(counted_presence_before - 1, counted_presence_after) def test_logentry_get_admin_url(self): "LogEntry.get_admin_url returns a URL to edit the entry's object or None for non-existent (possibly deleted) models" log_entry_name = "Model with string primary key" # capitalized in Recent Actions logentry = LogEntry.objects.get(content_type__name__iexact=log_entry_name) model = "modelwithstringprimarykey" desired_admin_url = "/test_admin/admin/admin_views/%s/%s/" % (model, iri_to_uri(quote(self.pk))) self.assertEqual(logentry.get_admin_url(), desired_admin_url) logentry.content_type.model = "non-existent" self.assertEqual(logentry.get_admin_url(), None) def test_deleteconfirmation_link(self): "The link from the delete confirmation page referring back to the changeform of the object should be quoted" response = self.client.get('/test_admin/admin/admin_views/modelwithstringprimarykey/%s/delete/' % quote(self.pk)) # this URL now comes through reverse(), thus url quoting and iri_to_uri encoding should_contain = """/%s/">%s""" % (escape(iri_to_uri(quote(self.pk))), escape(self.pk)) self.assertContains(response, should_contain) def test_url_conflicts_with_add(self): "A model with a primary key that ends with add should be visible" add_model = ModelWithStringPrimaryKey(pk="i have something to add") add_model.save() response = self.client.get('/test_admin/admin/admin_views/modelwithstringprimarykey/%s/' % quote(add_model.pk)) should_contain = """

      Change model with string primary key

      """ self.assertContains(response, should_contain) def test_url_conflicts_with_delete(self): "A model with a primary key that ends with delete should be visible" delete_model = ModelWithStringPrimaryKey(pk="delete") delete_model.save() response = self.client.get('/test_admin/admin/admin_views/modelwithstringprimarykey/%s/' % quote(delete_model.pk)) should_contain = """

      Change model with string primary key

      """ self.assertContains(response, should_contain) def test_url_conflicts_with_history(self): "A model with a primary key that ends with history should be visible" history_model = ModelWithStringPrimaryKey(pk="history") history_model.save() response = self.client.get('/test_admin/admin/admin_views/modelwithstringprimarykey/%s/' % quote(history_model.pk)) should_contain = """

      Change model with string primary key

      """ self.assertContains(response, should_contain) def test_shortcut_view_with_escaping(self): "'View on site should' work properly with char fields" model = ModelWithStringPrimaryKey(pk='abc_123') model.save() response = self.client.get('/test_admin/admin/admin_views/modelwithstringprimarykey/%s/' % quote(model.pk)) should_contain = '/%s/" class="viewsitelink">' % model.pk self.assertContains(response, should_contain) def test_change_view_history_link(self): """Object history button link should work and contain the pk value quoted.""" url = reverse('admin:%s_modelwithstringprimarykey_change' % ModelWithStringPrimaryKey._meta.app_label, args=(quote(self.pk),)) response = self.client.get(url) self.assertEqual(response.status_code, 200) expected_link = reverse('admin:%s_modelwithstringprimarykey_history' % ModelWithStringPrimaryKey._meta.app_label, args=(quote(self.pk),)) self.assertContains(response, '%d' % (link1, story1.id), 1) self.assertContains(response, '%d' % (link2, story2.id), 1) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class AdminSearchTest(TestCase): fixtures = ['admin-views-users', 'multiple-child-classes', 'admin-views-person'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_search_on_sibling_models(self): "Check that a search that mentions sibling models" response = self.client.get('/test_admin/admin/admin_views/recommendation/?q=bar') # confirm the search returned 1 object self.assertContains(response, "\n1 recommendation\n") def test_with_fk_to_field(self): """Ensure that the to_field GET parameter is preserved when a search is performed. Refs #10918. """ response = self.client.get('/test_admin/admin/auth/user/?q=joe&%s=id' % TO_FIELD_VAR) self.assertContains(response, "\n1 user\n") self.assertContains(response, '' % TO_FIELD_VAR, html=True) def test_exact_matches(self): response = self.client.get('/test_admin/admin/admin_views/recommendation/?q=bar') # confirm the search returned one object self.assertContains(response, "\n1 recommendation\n") response = self.client.get('/test_admin/admin/admin_views/recommendation/?q=ba') # confirm the search returned zero objects self.assertContains(response, "\n0 recommendations\n") def test_beginning_matches(self): response = self.client.get('/test_admin/admin/admin_views/person/?q=Gui') # confirm the search returned one object self.assertContains(response, "\n1 person\n") self.assertContains(response, "Guido") response = self.client.get('/test_admin/admin/admin_views/person/?q=uido') # confirm the search returned zero objects self.assertContains(response, "\n0 persons\n") self.assertNotContains(response, "Guido") def test_pluggable_search(self): PluggableSearchPerson.objects.create(name="Bob", age=10) PluggableSearchPerson.objects.create(name="Amy", age=20) response = self.client.get('/test_admin/admin/admin_views/pluggablesearchperson/?q=Bob') # confirm the search returned one object self.assertContains(response, "\n1 pluggable search person\n") self.assertContains(response, "Bob") response = self.client.get('/test_admin/admin/admin_views/pluggablesearchperson/?q=20') # confirm the search returned one object self.assertContains(response, "\n1 pluggable search person\n") self.assertContains(response, "Amy") def test_reset_link(self): """ Test presence of reset link in search bar ("1 result (_x total_)"). """ response = self.client.get('/test_admin/admin/admin_views/person/?q=Gui') self.assertContains(response, """1 result (3 total)""", html=True) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class AdminInheritedInlinesTest(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_inline(self): "Ensure that inline models which inherit from a common parent are correctly handled by admin." foo_user = "foo username" bar_user = "bar username" name_re = re.compile(b'name="(.*?)"') # test the add case response = self.client.get('/test_admin/admin/admin_views/persona/add/') names = name_re.findall(response.content) # make sure we have no duplicate HTML names self.assertEqual(len(names), len(set(names))) # test the add case post_data = { "name": "Test Name", # inline data "accounts-TOTAL_FORMS": "1", "accounts-INITIAL_FORMS": "0", "accounts-MAX_NUM_FORMS": "0", "accounts-0-username": foo_user, "accounts-2-TOTAL_FORMS": "1", "accounts-2-INITIAL_FORMS": "0", "accounts-2-MAX_NUM_FORMS": "0", "accounts-2-0-username": bar_user, } response = self.client.post('/test_admin/admin/admin_views/persona/add/', post_data) self.assertEqual(response.status_code, 302) # redirect somewhere self.assertEqual(Persona.objects.count(), 1) self.assertEqual(FooAccount.objects.count(), 1) self.assertEqual(BarAccount.objects.count(), 1) self.assertEqual(FooAccount.objects.all()[0].username, foo_user) self.assertEqual(BarAccount.objects.all()[0].username, bar_user) self.assertEqual(Persona.objects.all()[0].accounts.count(), 2) persona_id = Persona.objects.all()[0].id foo_id = FooAccount.objects.all()[0].id bar_id = BarAccount.objects.all()[0].id # test the edit case response = self.client.get('/test_admin/admin/admin_views/persona/%d/' % persona_id) names = name_re.findall(response.content) # make sure we have no duplicate HTML names self.assertEqual(len(names), len(set(names))) post_data = { "name": "Test Name", "accounts-TOTAL_FORMS": "2", "accounts-INITIAL_FORMS": "1", "accounts-MAX_NUM_FORMS": "0", "accounts-0-username": "%s-1" % foo_user, "accounts-0-account_ptr": str(foo_id), "accounts-0-persona": str(persona_id), "accounts-2-TOTAL_FORMS": "2", "accounts-2-INITIAL_FORMS": "1", "accounts-2-MAX_NUM_FORMS": "0", "accounts-2-0-username": "%s-1" % bar_user, "accounts-2-0-account_ptr": str(bar_id), "accounts-2-0-persona": str(persona_id), } response = self.client.post('/test_admin/admin/admin_views/persona/%d/' % persona_id, post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Persona.objects.count(), 1) self.assertEqual(FooAccount.objects.count(), 1) self.assertEqual(BarAccount.objects.count(), 1) self.assertEqual(FooAccount.objects.all()[0].username, "%s-1" % foo_user) self.assertEqual(BarAccount.objects.all()[0].username, "%s-1" % bar_user) self.assertEqual(Persona.objects.all()[0].accounts.count(), 2) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class AdminActionsTest(TestCase): fixtures = ['admin-views-users.xml', 'admin-views-actions.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_model_admin_custom_action(self): "Tests a custom action defined in a ModelAdmin method" action_data = { ACTION_CHECKBOX_NAME: [1], 'action': 'mail_admin', 'index': 0, } self.client.post('/test_admin/admin/admin_views/subscriber/', action_data) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Greetings from a ModelAdmin action') def test_model_admin_default_delete_action(self): "Tests the default delete action defined as a ModelAdmin method" action_data = { ACTION_CHECKBOX_NAME: [1, 2], 'action': 'delete_selected', 'index': 0, } delete_confirmation_data = { ACTION_CHECKBOX_NAME: [1, 2], 'action': 'delete_selected', 'post': 'yes', } confirmation = self.client.post('/test_admin/admin/admin_views/subscriber/', action_data) self.assertIsInstance(confirmation, TemplateResponse) self.assertContains(confirmation, "Are you sure you want to delete the selected subscribers?") self.assertContains(confirmation, "

      Summary

      ") self.assertContains(confirmation, "
    • Subscribers: 3
    • ") self.assertContains(confirmation, "
    • External subscribers: 1
    • ") self.assertContains(confirmation, ACTION_CHECKBOX_NAME, count=2) self.client.post('/test_admin/admin/admin_views/subscriber/', delete_confirmation_data) self.assertEqual(Subscriber.objects.count(), 0) @override_settings(USE_THOUSAND_SEPARATOR=True, USE_L10N=True) def test_non_localized_pk(self): """If USE_THOUSAND_SEPARATOR is set, make sure that the ids for the objects selected for deletion are rendered without separators. Refs #14895. """ subscriber = Subscriber.objects.get(id=1) subscriber.id = 9999 subscriber.save() action_data = { ACTION_CHECKBOX_NAME: [9999, 2], 'action': 'delete_selected', 'index': 0, } response = self.client.post('/test_admin/admin/admin_views/subscriber/', action_data) self.assertTemplateUsed(response, 'admin/delete_selected_confirmation.html') self.assertContains(response, 'value="9999"') # Instead of 9,999 self.assertContains(response, 'value="2"') def test_model_admin_default_delete_action_protected(self): """ Tests the default delete action defined as a ModelAdmin method in the case where some related objects are protected from deletion. """ q1 = Question.objects.create(question="Why?") a1 = Answer.objects.create(question=q1, answer="Because.") a2 = Answer.objects.create(question=q1, answer="Yes.") q2 = Question.objects.create(question="Wherefore?") action_data = { ACTION_CHECKBOX_NAME: [q1.pk, q2.pk], 'action': 'delete_selected', 'index': 0, } response = self.client.post("/test_admin/admin/admin_views/question/", action_data) self.assertContains(response, "would require deleting the following protected related objects") self.assertContains(response, '
    • Answer: Because.
    • ' % a1.pk, html=True) self.assertContains(response, '
    • Answer: Yes.
    • ' % a2.pk, html=True) def test_model_admin_default_delete_action_no_change_url(self): """ Default delete action shouldn't break if a user's ModelAdmin removes the url for change_view. Regression test for #20640 """ obj = UnchangeableObject.objects.create() action_data = { ACTION_CHECKBOX_NAME: obj.pk, "action": "delete_selected", "index": "0", } response = self.client.post('/test_admin/admin/admin_views/unchangeableobject/', action_data) # No 500 caused by NoReverseMatch self.assertEqual(response.status_code, 200) # The page shouldn't display a link to the nonexistent change page self.assertContains(response, "
    • Unchangeable object: UnchangeableObject object
    • ", 1, html=True) def test_custom_function_mail_action(self): "Tests a custom action defined in a function" action_data = { ACTION_CHECKBOX_NAME: [1], 'action': 'external_mail', 'index': 0, } self.client.post('/test_admin/admin/admin_views/externalsubscriber/', action_data) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Greetings from a function action') def test_custom_function_action_with_redirect(self): "Tests a custom action defined in a function" action_data = { ACTION_CHECKBOX_NAME: [1], 'action': 'redirect_to', 'index': 0, } response = self.client.post('/test_admin/admin/admin_views/externalsubscriber/', action_data) self.assertEqual(response.status_code, 302) def test_default_redirect(self): """ Test that actions which don't return an HttpResponse are redirected to the same page, retaining the querystring (which may contain changelist information). """ action_data = { ACTION_CHECKBOX_NAME: [1], 'action': 'external_mail', 'index': 0, } url = '/test_admin/admin/admin_views/externalsubscriber/?o=1' response = self.client.post(url, action_data) self.assertRedirects(response, url) def test_custom_function_action_streaming_response(self): """Tests a custom action that returns a StreamingHttpResponse.""" action_data = { ACTION_CHECKBOX_NAME: [1], 'action': 'download', 'index': 0, } response = self.client.post('/test_admin/admin/admin_views/externalsubscriber/', action_data) content = b''.join(response.streaming_content) self.assertEqual(content, b'This is the content of the file') self.assertEqual(response.status_code, 200) def test_custom_function_action_no_perm_response(self): """Tests a custom action that returns an HttpResponse with 403 code.""" action_data = { ACTION_CHECKBOX_NAME: [1], 'action': 'no_perm', 'index': 0, } response = self.client.post('/test_admin/admin/admin_views/externalsubscriber/', action_data) self.assertEqual(response.status_code, 403) self.assertEqual(response.content, b'No permission to perform this action') def test_actions_ordering(self): """ Ensure that actions are ordered as expected. Refs #15964. """ response = self.client.get('/test_admin/admin/admin_views/externalsubscriber/') self.assertContains(response, '''") self.assertContains(response, "Very awesome.") self.assertContains(response, "Unknown coolness.") self.assertContains(response, "foo") # Checks that multiline text in a readonly field gets
      tags self.assertContains(response, "Multiline
      test
      string") self.assertContains(response, "

      Multiline
      html
      content

      ", html=True) self.assertContains(response, "InlineMultiline
      test
      string") self.assertContains(response, formats.localize(datetime.date.today() - datetime.timedelta(days=7))) self.assertContains(response, '
      ') self.assertContains(response, '
      ') self.assertContains(response, '
      ') self.assertContains(response, '
      ') self.assertContains(response, '
      ') self.assertContains(response, '

      ', 3) self.assertContains(response, '

      Some help text for the title (with unicode ŠĐĆŽćžšđ)

      ', html=True) self.assertContains(response, '

      Some help text for the content (with unicode ŠĐĆŽćžšđ)

      ', html=True) self.assertContains(response, '

      Some help text for the date (with unicode ŠĐĆŽćžšđ)

      ', html=True) p = Post.objects.create(title="I worked on readonly_fields", content="Its good stuff") response = self.client.get('/test_admin/admin/admin_views/post/%d/' % p.pk) self.assertContains(response, "%d amount of cool" % p.pk) def test_readonly_post(self): data = { "title": "Django Got Readonly Fields", "content": "This is an incredible development.", "link_set-TOTAL_FORMS": "1", "link_set-INITIAL_FORMS": "0", "link_set-MAX_NUM_FORMS": "0", } response = self.client.post('/test_admin/admin/admin_views/post/add/', data) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 1) p = Post.objects.get() self.assertEqual(p.posted, datetime.date.today()) data["posted"] = "10-8-1990" # some date that's not today response = self.client.post('/test_admin/admin/admin_views/post/add/', data) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 2) p = Post.objects.order_by('-id')[0] self.assertEqual(p.posted, datetime.date.today()) def test_readonly_manytomany(self): "Regression test for #13004" response = self.client.get('/test_admin/admin/admin_views/pizza/add/') self.assertEqual(response.status_code, 200) def test_user_password_change_limited_queryset(self): su = User.objects.filter(is_superuser=True)[0] response = self.client.get('/test_admin/admin2/auth/user/%s/password/' % su.pk) self.assertEqual(response.status_code, 404) def test_change_form_renders_correct_null_choice_value(self): """ Regression test for #17911. """ choice = Choice.objects.create(choice=None) response = self.client.get('/test_admin/admin/admin_views/choice/%s/' % choice.pk) self.assertContains(response, '

      No opinion

      ', html=True) self.assertNotContains(response, '

      (None)

      ') def test_readonly_backwards_ref(self): """ Regression test for #16433 - backwards references for related objects broke if the related field is read-only due to the help_text attribute """ topping = Topping.objects.create(name='Salami') pizza = Pizza.objects.create(name='Americano') pizza.toppings.add(topping) response = self.client.get('/test_admin/admin/admin_views/topping/add/') self.assertEqual(response.status_code, 200) def test_readonly_field_overrides(self): """ Regression test for #22087 - ModelForm Meta overrides are ignored by AdminReadonlyField """ p = FieldOverridePost.objects.create(title="Test Post", content="Test Content") response = self.client.get('/test_admin/admin/admin_views/fieldoverridepost/%d/' % p.pk) self.assertEqual(response.status_code, 200) self.assertContains(response, '

      Overridden help text for the date

      ') self.assertContains(response, '', html=True) self.assertNotContains(response, "Some help text for the date (with unicode ŠĐĆŽćžšđ)") @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class LimitChoicesToInAdminTest(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_limit_choices_to_as_callable(self): """Test for ticket 2445 changes to admin.""" threepwood = Character.objects.create( username='threepwood', last_action=datetime.datetime.today() + datetime.timedelta(days=1), ) marley = Character.objects.create( username='marley', last_action=datetime.datetime.today() - datetime.timedelta(days=1), ) response = self.client.get('/test_admin/admin/admin_views/stumpjoke/add/') # The allowed option should appear twice; the limited option should not appear. self.assertContains(response, threepwood.username, count=2) self.assertNotContains(response, marley.username) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class RawIdFieldsTest(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_limit_choices_to(self): """Regression test for 14880""" actor = Actor.objects.create(name="Palin", age=27) Inquisition.objects.create(expected=True, leader=actor, country="England") Inquisition.objects.create(expected=False, leader=actor, country="Spain") response = self.client.get('/test_admin/admin/admin_views/sketch/add/') # Find the link m = re.search(br']* id="lookup_id_inquisition"', response.content) self.assertTrue(m) # Got a match popup_url = m.groups()[0].decode().replace("&", "&") # Handle relative links popup_url = urljoin(response.request['PATH_INFO'], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step also tests integers, strings and booleans in the # lookup query string; in model we define inquisition field to have a # limit_choices_to option that includes a filter on a string field # (inquisition__actor__name), a filter on an integer field # (inquisition__actor__age), and a filter on a boolean field # (inquisition__expected). response2 = self.client.get(popup_url) self.assertContains(response2, "Spain") self.assertNotContains(response2, "England") def test_limit_choices_to_isnull_false(self): """Regression test for 20182""" Actor.objects.create(name="Palin", age=27) Actor.objects.create(name="Kilbraken", age=50, title="Judge") response = self.client.get('/test_admin/admin/admin_views/sketch/add/') # Find the link m = re.search(br']* id="lookup_id_defendant0"', response.content) self.assertTrue(m) # Got a match popup_url = m.groups()[0].decode().replace("&", "&") # Handle relative links popup_url = urljoin(response.request['PATH_INFO'], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step tests field__isnull=0 gets parsed correctly from the # lookup query string; in model we define defendant0 field to have a # limit_choices_to option that includes "actor__title__isnull=False". response2 = self.client.get(popup_url) self.assertContains(response2, "Kilbraken") self.assertNotContains(response2, "Palin") def test_limit_choices_to_isnull_true(self): """Regression test for 20182""" Actor.objects.create(name="Palin", age=27) Actor.objects.create(name="Kilbraken", age=50, title="Judge") response = self.client.get('/test_admin/admin/admin_views/sketch/add/') # Find the link m = re.search(br']* id="lookup_id_defendant1"', response.content) self.assertTrue(m) # Got a match popup_url = m.groups()[0].decode().replace("&", "&") # Handle relative links popup_url = urljoin(response.request['PATH_INFO'], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step tests field__isnull=1 gets parsed correctly from the # lookup query string; in model we define defendant1 field to have a # limit_choices_to option that includes "actor__title__isnull=True". response2 = self.client.get(popup_url) self.assertNotContains(response2, "Kilbraken") self.assertContains(response2, "Palin") @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class UserAdminTest(TestCase): """ Tests user CRUD functionality. """ fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_save_button(self): user_count = User.objects.count() response = self.client.post('/test_admin/admin/auth/user/add/', { 'username': 'newuser', 'password1': 'newpassword', 'password2': 'newpassword', }) new_user = User.objects.order_by('-id')[0] self.assertRedirects(response, '/test_admin/admin/auth/user/%s/' % new_user.pk) self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) def test_save_continue_editing_button(self): user_count = User.objects.count() response = self.client.post('/test_admin/admin/auth/user/add/', { 'username': 'newuser', 'password1': 'newpassword', 'password2': 'newpassword', '_continue': '1', }) new_user = User.objects.order_by('-id')[0] self.assertRedirects(response, '/test_admin/admin/auth/user/%s/' % new_user.pk) self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) def test_password_mismatch(self): response = self.client.post('/test_admin/admin/auth/user/add/', { 'username': 'newuser', 'password1': 'newpassword', 'password2': 'mismatch', }) self.assertEqual(response.status_code, 200) adminform = response.context['adminform'] self.assertTrue('password' not in adminform.form.errors) self.assertEqual(adminform.form.errors['password2'], ["The two password fields didn't match."]) def test_user_fk_popup(self): """Quick user addition in a FK popup shouldn't invoke view for further user customization""" response = self.client.get('/test_admin/admin/admin_views/album/add/') self.assertEqual(response.status_code, 200) self.assertContains(response, '/test_admin/admin/auth/user/add') self.assertContains(response, 'class="add-another" id="add_id_owner"') response = self.client.get('/test_admin/admin/auth/user/add/?_popup=1') self.assertEqual(response.status_code, 200) self.assertNotContains(response, 'name="_continue"') self.assertNotContains(response, 'name="_addanother"') data = { 'username': 'newuser', 'password1': 'newpassword', 'password2': 'newpassword', '_popup': '1', '_save': '1', } response = self.client.post('/test_admin/admin/auth/user/add/?_popup=1', data, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, 'dismissAddAnotherPopup') def test_save_add_another_button(self): user_count = User.objects.count() response = self.client.post('/test_admin/admin/auth/user/add/', { 'username': 'newuser', 'password1': 'newpassword', 'password2': 'newpassword', '_addanother': '1', }) new_user = User.objects.order_by('-id')[0] self.assertRedirects(response, '/test_admin/admin/auth/user/add/') self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) def test_user_permission_performance(self): u = User.objects.all()[0] # Don't depend on a warm cache, see #17377. ContentType.objects.clear_cache() with self.assertNumQueries(10): response = self.client.get('/test_admin/admin/auth/user/%s/' % u.pk) self.assertEqual(response.status_code, 200) def test_form_url_present_in_context(self): u = User.objects.all()[0] response = self.client.get('/test_admin/admin3/auth/user/%s/password/' % u.pk) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['form_url'], 'pony') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class GroupAdminTest(TestCase): """ Tests group CRUD functionality. """ fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_save_button(self): group_count = Group.objects.count() response = self.client.post('/test_admin/admin/auth/group/add/', { 'name': 'newgroup', }) Group.objects.order_by('-id')[0] self.assertRedirects(response, '/test_admin/admin/auth/group/') self.assertEqual(Group.objects.count(), group_count + 1) def test_group_permission_performance(self): g = Group.objects.create(name="test_group") with self.assertNumQueries(8): response = self.client.get('/test_admin/admin/auth/group/%s/' % g.pk) self.assertEqual(response.status_code, 200) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class CSSTest(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_field_prefix_css_classes(self): """ Ensure that fields have a CSS class name with a 'field-' prefix. Refs #16371. """ response = self.client.get('/test_admin/admin/admin_views/post/add/') # The main form self.assertContains(response, 'class="form-row field-title"') self.assertContains(response, 'class="form-row field-content"') self.assertContains(response, 'class="form-row field-public"') self.assertContains(response, 'class="form-row field-awesomeness_level"') self.assertContains(response, 'class="form-row field-coolness"') self.assertContains(response, 'class="form-row field-value"') self.assertContains(response, 'class="form-row"') # The lambda function # The tabular inline self.assertContains(response, '') self.assertContains(response, '') def test_index_css_classes(self): """ Ensure that CSS class names are used for each app and model on the admin index pages. Refs #17050. """ # General index page response = self.client.get("/test_admin/admin/") self.assertContains(response, '
      ') self.assertContains(response, '') self.assertContains(response, '') # App index page response = self.client.get("/test_admin/admin/admin_views/") self.assertContains(response, '
      ') self.assertContains(response, '') self.assertContains(response, '') def test_app_model_in_form_body_class(self): """ Ensure app and model tag are correctly read by change_form template """ response = self.client.get('/test_admin/admin/admin_views/section/add/') self.assertEqual(response.status_code, 200) self.assertContains(response, '') self.assertContains( response, '') self.assertContains( response, '') try: import docutils except ImportError: docutils = None @unittest.skipUnless(docutils, "no docutils installed.") @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") @modify_settings(INSTALLED_APPS={'append': ['django.contrib.admindocs', 'django.contrib.flatpages']}) class AdminDocsTest(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_tags(self): response = self.client.get('/test_admin/admin/doc/tags/') # The builtin tag group exists self.assertContains(response, "

      Built-in tags

      ", count=2, html=True) # A builtin tag exists in both the index and detail self.assertContains(response, '

      autoescape

      ', html=True) self.assertContains(response, '
    • autoescape
    • ', html=True) # An app tag exists in both the index and detail self.assertContains(response, '

      get_flatpages

      ', html=True) self.assertContains(response, '
    • get_flatpages
    • ', html=True) # The admin list tag group exists self.assertContains(response, "

      admin_list

      ", count=2, html=True) # An admin list tag exists in both the index and detail self.assertContains(response, '

      admin_actions

      ', html=True) self.assertContains(response, '
    • admin_actions
    • ', html=True) def test_filters(self): response = self.client.get('/test_admin/admin/doc/filters/') # The builtin filter group exists self.assertContains(response, "

      Built-in filters

      ", count=2, html=True) # A builtin filter exists in both the index and detail self.assertContains(response, '

      add

      ', html=True) self.assertContains(response, '
    • add
    • ', html=True) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class ValidXHTMLTests(TestCase): fixtures = ['admin-views-users.xml'] urlbit = 'admin' def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() @override_settings( TEMPLATE_CONTEXT_PROCESSORS=filter( lambda t: t != 'django.core.context_processors.i18n', global_settings.TEMPLATE_CONTEXT_PROCESSORS), USE_I18N=False, ) def test_lang_name_present(self): response = self.client.get('/test_admin/%s/admin_views/' % self.urlbit) self.assertNotContains(response, ' lang=""') self.assertNotContains(response, ' xml:lang=""') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls", USE_THOUSAND_SEPARATOR=True, USE_L10N=True) class DateHierarchyTests(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): formats.reset_format_cache() def assert_non_localized_year(self, response, year): """Ensure that the year is not localized with USE_THOUSAND_SEPARATOR. Refs #15234. """ self.assertNotContains(response, formats.number_format(year)) def assert_contains_year_link(self, response, date): self.assertContains(response, '?release_date__year=%d"' % (date.year,)) def assert_contains_month_link(self, response, date): self.assertContains( response, '?release_date__month=%d&release_date__year=%d"' % ( date.month, date.year)) def assert_contains_day_link(self, response, date): self.assertContains( response, '?release_date__day=%d&' 'release_date__month=%d&release_date__year=%d"' % ( date.day, date.month, date.year)) def test_empty(self): """ Ensure that no date hierarchy links display with empty changelist. """ response = self.client.get( reverse('admin:admin_views_podcast_changelist')) self.assertNotContains(response, 'release_date__year=') self.assertNotContains(response, 'release_date__month=') self.assertNotContains(response, 'release_date__day=') def test_single(self): """ Ensure that single day-level date hierarchy appears for single object. """ DATE = datetime.date(2000, 6, 30) Podcast.objects.create(release_date=DATE) url = reverse('admin:admin_views_podcast_changelist') response = self.client.get(url) self.assert_contains_day_link(response, DATE) self.assert_non_localized_year(response, 2000) def test_within_month(self): """ Ensure that day-level links appear for changelist within single month. """ DATES = (datetime.date(2000, 6, 30), datetime.date(2000, 6, 15), datetime.date(2000, 6, 3)) for date in DATES: Podcast.objects.create(release_date=date) url = reverse('admin:admin_views_podcast_changelist') response = self.client.get(url) for date in DATES: self.assert_contains_day_link(response, date) self.assert_non_localized_year(response, 2000) def test_within_year(self): """ Ensure that month-level links appear for changelist within single year. """ DATES = (datetime.date(2000, 1, 30), datetime.date(2000, 3, 15), datetime.date(2000, 5, 3)) for date in DATES: Podcast.objects.create(release_date=date) url = reverse('admin:admin_views_podcast_changelist') response = self.client.get(url) # no day-level links self.assertNotContains(response, 'release_date__day=') for date in DATES: self.assert_contains_month_link(response, date) self.assert_non_localized_year(response, 2000) def test_multiple_years(self): """ Ensure that year-level links appear for year-spanning changelist. """ DATES = (datetime.date(2001, 1, 30), datetime.date(2003, 3, 15), datetime.date(2005, 5, 3)) for date in DATES: Podcast.objects.create(release_date=date) response = self.client.get( reverse('admin:admin_views_podcast_changelist')) # no day/month-level links self.assertNotContains(response, 'release_date__day=') self.assertNotContains(response, 'release_date__month=') for date in DATES: self.assert_contains_year_link(response, date) # and make sure GET parameters still behave correctly for date in DATES: url = '%s?release_date__year=%d' % ( reverse('admin:admin_views_podcast_changelist'), date.year) response = self.client.get(url) self.assert_contains_month_link(response, date) self.assert_non_localized_year(response, 2000) self.assert_non_localized_year(response, 2003) self.assert_non_localized_year(response, 2005) url = '%s?release_date__year=%d&release_date__month=%d' % ( reverse('admin:admin_views_podcast_changelist'), date.year, date.month) response = self.client.get(url) self.assert_contains_day_link(response, date) self.assert_non_localized_year(response, 2000) self.assert_non_localized_year(response, 2003) self.assert_non_localized_year(response, 2005) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class AdminCustomSaveRelatedTests(TestCase): """ Ensure that one can easily customize the way related objects are saved. Refs #16115. """ fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def test_should_be_able_to_edit_related_objects_on_add_view(self): post = { 'child_set-TOTAL_FORMS': '3', 'child_set-INITIAL_FORMS': '0', 'name': 'Josh Stone', 'child_set-0-name': 'Paul', 'child_set-1-name': 'Catherine', } self.client.post('/test_admin/admin/admin_views/parent/add/', post) self.assertEqual(1, Parent.objects.count()) self.assertEqual(2, Child.objects.count()) children_names = list(Child.objects.order_by('name').values_list('name', flat=True)) self.assertEqual('Josh Stone', Parent.objects.latest('id').name) self.assertEqual(['Catherine Stone', 'Paul Stone'], children_names) def test_should_be_able_to_edit_related_objects_on_change_view(self): parent = Parent.objects.create(name='Josh Stone') paul = Child.objects.create(parent=parent, name='Paul') catherine = Child.objects.create(parent=parent, name='Catherine') post = { 'child_set-TOTAL_FORMS': '5', 'child_set-INITIAL_FORMS': '2', 'name': 'Josh Stone', 'child_set-0-name': 'Paul', 'child_set-0-id': paul.id, 'child_set-1-name': 'Catherine', 'child_set-1-id': catherine.id, } self.client.post('/test_admin/admin/admin_views/parent/%s/' % parent.id, post) children_names = list(Child.objects.order_by('name').values_list('name', flat=True)) self.assertEqual('Josh Stone', Parent.objects.latest('id').name) self.assertEqual(['Catherine Stone', 'Paul Stone'], children_names) def test_should_be_able_to_edit_related_objects_on_changelist_view(self): parent = Parent.objects.create(name='Josh Rock') Child.objects.create(parent=parent, name='Paul') Child.objects.create(parent=parent, name='Catherine') post = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '0', 'form-0-id': parent.id, 'form-0-name': 'Josh Stone', '_save': 'Save' } self.client.post('/test_admin/admin/admin_views/parent/', post) children_names = list(Child.objects.order_by('name').values_list('name', flat=True)) self.assertEqual('Josh Stone', Parent.objects.latest('id').name) self.assertEqual(['Catherine Stone', 'Paul Stone'], children_names) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class AdminViewLogoutTest(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_client_logout_url_can_be_used_to_login(self): response = self.client.get('/test_admin/admin/logout/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'registration/logged_out.html') self.assertEqual(response.request['PATH_INFO'], '/test_admin/admin/logout/') # we are now logged out response = self.client.get('/test_admin/admin/logout/') self.assertEqual(response.status_code, 302) # we should be redirected to the login page. # follow the redirect and test results. response = self.client.get('/test_admin/admin/logout/', follow=True) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'admin/login.html') self.assertEqual(response.request['PATH_INFO'], '/test_admin/admin/login/') self.assertContains(response, '') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class AdminUserMessageTest(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def send_message(self, level): """ Helper that sends a post to the dummy test methods and asserts that a message with the level has appeared in the response. """ action_data = { ACTION_CHECKBOX_NAME: [1], 'action': 'message_%s' % level, 'index': 0, } response = self.client.post('/test_admin/admin/admin_views/usermessenger/', action_data, follow=True) self.assertContains(response, '
    • Test %s
    • ' % (level, level), html=True) @override_settings(MESSAGE_LEVEL=10) # Set to DEBUG for this request def test_message_debug(self): self.send_message('debug') def test_message_info(self): self.send_message('info') def test_message_success(self): self.send_message('success') def test_message_warning(self): self.send_message('warning') def test_message_error(self): self.send_message('error') def test_message_extra_tags(self): action_data = { ACTION_CHECKBOX_NAME: [1], 'action': 'message_extra_tags', 'index': 0, } response = self.client.post('/test_admin/admin/admin_views/usermessenger/', action_data, follow=True) self.assertContains(response, '
    • Test tags
    • ', html=True) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class AdminKeepChangeListFiltersTests(TestCase): fixtures = ['admin-views-users.xml'] admin_site = site def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def assertURLEqual(self, url1, url2): """ Assert that two URLs are equal despite the ordering of their querystring. Refs #22360. """ parsed_url1 = urlparse(url1) path1 = parsed_url1.path parsed_qs1 = dict(parse_qsl(parsed_url1.query)) parsed_url2 = urlparse(url2) path2 = parsed_url2.path parsed_qs2 = dict(parse_qsl(parsed_url2.query)) for parsed_qs in [parsed_qs1, parsed_qs2]: if '_changelist_filters' in parsed_qs: changelist_filters = parsed_qs['_changelist_filters'] parsed_filters = dict(parse_qsl(changelist_filters)) parsed_qs['_changelist_filters'] = parsed_filters self.assertEqual(path1, path2) self.assertEqual(parsed_qs1, parsed_qs2) def test_assert_url_equal(self): # Test equality. self.assertURLEqual( 'http://testserver/test_admin/admin/auth/user/105/?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0', 'http://testserver/test_admin/admin/auth/user/105/?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0' ) # Test inequality. with self.assertRaises(AssertionError): self.assertURLEqual( 'http://testserver/test_admin/admin/auth/user/105/?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0', 'http://testserver/test_admin/admin/auth/user/105/?_changelist_filters=is_staff__exact%3D1%26is_superuser__exact%3D1' ) # Ignore scheme and host. self.assertURLEqual( 'http://testserver/test_admin/admin/auth/user/105/?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0', '/test_admin/admin/auth/user/105/?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0' ) # Ignore ordering of querystring. self.assertURLEqual( '/test_admin/admin/auth/user/?is_staff__exact=0&is_superuser__exact=0', '/test_admin/admin/auth/user/?is_superuser__exact=0&is_staff__exact=0' ) # Ignore ordering of _changelist_filters. self.assertURLEqual( '/test_admin/admin/auth/user/105/?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0', '/test_admin/admin/auth/user/105/?_changelist_filters=is_superuser__exact%3D0%26is_staff__exact%3D0' ) def get_changelist_filters(self): return { 'is_superuser__exact': 0, 'is_staff__exact': 0, } def get_changelist_filters_querystring(self): return urlencode(self.get_changelist_filters()) def get_preserved_filters_querystring(self): return urlencode({ '_changelist_filters': self.get_changelist_filters_querystring() }) def get_sample_user_id(self): return 104 def get_changelist_url(self): return '%s?%s' % ( reverse('admin:auth_user_changelist', current_app=self.admin_site.name), self.get_changelist_filters_querystring(), ) def get_add_url(self): return '%s?%s' % ( reverse('admin:auth_user_add', current_app=self.admin_site.name), self.get_preserved_filters_querystring(), ) def get_change_url(self, user_id=None): if user_id is None: user_id = self.get_sample_user_id() return "%s?%s" % ( reverse('admin:auth_user_change', args=(user_id,), current_app=self.admin_site.name), self.get_preserved_filters_querystring(), ) def get_history_url(self, user_id=None): if user_id is None: user_id = self.get_sample_user_id() return "%s?%s" % ( reverse('admin:auth_user_history', args=(user_id,), current_app=self.admin_site.name), self.get_preserved_filters_querystring(), ) def get_delete_url(self, user_id=None): if user_id is None: user_id = self.get_sample_user_id() return "%s?%s" % ( reverse('admin:auth_user_delete', args=(user_id,), current_app=self.admin_site.name), self.get_preserved_filters_querystring(), ) def test_changelist_view(self): response = self.client.get(self.get_changelist_url()) self.assertEqual(response.status_code, 200) # Check the `change_view` link has the correct querystring. detail_link = re.search( 'joepublic', force_text(response.content) ) self.assertURLEqual(detail_link.group(1), self.get_change_url()) def test_change_view(self): # Get the `change_view`. response = self.client.get(self.get_change_url()) self.assertEqual(response.status_code, 200) # Check the form action. form_action = re.search( '
      ', force_text(response.content) ) self.assertURLEqual(form_action.group(1), '?%s' % self.get_preserved_filters_querystring()) # Check the history link. history_link = re.search( 'History', force_text(response.content) ) self.assertURLEqual(history_link.group(1), self.get_history_url()) # Check the delete link. delete_link = re.search( 'Delete', force_text(response.content) ) self.assertURLEqual(delete_link.group(1), self.get_delete_url()) # Test redirect on "Save". post_data = { 'username': 'joepublic', 'last_login_0': '2007-05-30', 'last_login_1': '13:20:10', 'date_joined_0': '2007-05-30', 'date_joined_1': '13:20:10', } post_data['_save'] = 1 response = self.client.post(self.get_change_url(), data=post_data) self.assertEqual(response.status_code, 302) self.assertURLEqual( response.url, self.get_changelist_url() ) post_data.pop('_save') # Test redirect on "Save and continue". post_data['_continue'] = 1 response = self.client.post(self.get_change_url(), data=post_data) self.assertEqual(response.status_code, 302) self.assertURLEqual( response.url, self.get_change_url() ) post_data.pop('_continue') # Test redirect on "Save and add new". post_data['_addanother'] = 1 response = self.client.post(self.get_change_url(), data=post_data) self.assertEqual(response.status_code, 302) self.assertURLEqual( response.url, self.get_add_url() ) post_data.pop('_addanother') def test_add_view(self): # Get the `add_view`. response = self.client.get(self.get_add_url()) self.assertEqual(response.status_code, 200) # Check the form action. form_action = re.search( '', force_text(response.content) ) self.assertURLEqual(form_action.group(1), '?%s' % self.get_preserved_filters_querystring()) post_data = { 'username': 'dummy', 'password1': 'test', 'password2': 'test', } # Test redirect on "Save". post_data['_save'] = 1 response = self.client.post(self.get_add_url(), data=post_data) self.assertEqual(response.status_code, 302) self.assertURLEqual( response.url, self.get_change_url(User.objects.latest('pk').pk) ) post_data.pop('_save') # Test redirect on "Save and continue". post_data['username'] = 'dummy2' post_data['_continue'] = 1 response = self.client.post(self.get_add_url(), data=post_data) self.assertEqual(response.status_code, 302) self.assertURLEqual( response.url, self.get_change_url(User.objects.latest('pk').pk) ) post_data.pop('_continue') # Test redirect on "Save and add new". post_data['username'] = 'dummy3' post_data['_addanother'] = 1 response = self.client.post(self.get_add_url(), data=post_data) self.assertEqual(response.status_code, 302) self.assertURLEqual( response.url, self.get_add_url() ) post_data.pop('_addanother') def test_delete_view(self): # Test redirect on "Delete". response = self.client.post(self.get_delete_url(), {'post': 'yes'}) self.assertEqual(response.status_code, 302) self.assertURLEqual( response.url, self.get_changelist_url() ) def test_url_prefix(self): context = { 'preserved_filters': self.get_preserved_filters_querystring(), 'opts': User._meta, } url = reverse('admin:auth_user_changelist', current_app=self.admin_site.name) self.assertURLEqual( self.get_changelist_url(), add_preserved_filters(context, url), ) original_prefix = get_script_prefix() try: set_script_prefix('/prefix/') url = reverse('admin:auth_user_changelist', current_app=self.admin_site.name) self.assertURLEqual( self.get_changelist_url(), add_preserved_filters(context, url), ) finally: set_script_prefix(original_prefix) class NamespacedAdminKeepChangeListFiltersTests(AdminKeepChangeListFiltersTests): admin_site = site2 @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF="admin_views.urls") class TestLabelVisibility(TestCase): """ #11277 -Labels of hidden fields in admin were not hidden. """ fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def test_all_fields_visible(self): response = self.client.get('/test_admin/admin/admin_views/emptymodelvisible/add/') self.assert_fieldline_visible(response) self.assert_field_visible(response, 'first') self.assert_field_visible(response, 'second') def test_all_fields_hidden(self): response = self.client.get('/test_admin/admin/admin_views/emptymodelhidden/add/') self.assert_fieldline_hidden(response) self.assert_field_hidden(response, 'first') self.assert_field_hidden(response, 'second') def test_mixin(self): response = self.client.get('/test_admin/admin/admin_views/emptymodelmixin/add/') self.assert_fieldline_visible(response) self.assert_field_hidden(response, 'first') self.assert_field_visible(response, 'second') def assert_field_visible(self, response, field_name): self.assertContains(response, '
      ' % field_name) def assert_field_hidden(self, response, field_name): self.assertContains(response, '