import datetime import os import re import unittest import zoneinfo from unittest import mock from urllib.parse import parse_qsl, urljoin, urlparse from django import forms from django.contrib import admin from django.contrib.admin import AdminSite, ModelAdmin from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.models import ADDITION, DELETION, LogEntry from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.admin.utils import quote from django.contrib.admin.views.main import IS_POPUP_VAR from django.contrib.auth import REDIRECT_FIELD_NAME, get_permission_codename from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import AdminPasswordChangeForm from django.contrib.auth.models import Group, Permission, User from django.contrib.contenttypes.models import ContentType from django.core import mail from django.core.checks import Error from django.core.files import temp as tempfile from django.db import connection from django.forms.utils import ErrorList from django.template.response import TemplateResponse from django.test import ( RequestFactory, TestCase, ignore_warnings, modify_settings, override_settings, skipUnlessDBFeature, ) from django.test.utils import override_script_prefix from django.urls import NoReverseMatch, resolve, reverse from django.utils import formats, translation from django.utils.cache import get_max_age from django.utils.deprecation import RemovedInDjango60Warning from django.utils.encoding import iri_to_uri from django.utils.html import escape from django.utils.http import urlencode from . import customadmin from .admin import CityAdmin, site, site2 from .models import ( Actor, AdminOrderedAdminMethod, AdminOrderedCallable, AdminOrderedField, AdminOrderedModelMethod, Album, Answer, Answer2, Article, BarAccount, Book, Bookmark, Box, Category, Chapter, ChapterXtra1, ChapterXtra2, Character, Child, Choice, City, Collector, Color, ComplexSortedPerson, CoverLetter, CustomArticle, CyclicOne, CyclicTwo, DooHickey, Employee, EmptyModel, Fabric, FancyDoodad, FieldOverridePost, FilteredManager, FooAccount, FoodDelivery, FunkyTag, Gallery, Grommet, Inquisition, Language, Link, MainPrepopulated, Media, ModelWithStringPrimaryKey, OtherStory, Paper, Parent, ParentWithDependentChildren, ParentWithUUIDPK, Person, Persona, Picture, Pizza, Plot, PlotDetails, PluggableSearchPerson, Podcast, Post, PrePopulatedPost, Promo, Question, ReadablePizza, ReadOnlyPizza, ReadOnlyRelatedField, Recommendation, Recommender, RelatedPrepopulated, RelatedWithUUIDPKModel, Report, Restaurant, RowLevelChangePermissionModel, SecretHideout, Section, ShortMessage, Simple, Song, State, Story, SuperSecretHideout, SuperVillain, Telegram, TitleTranslation, Topping, Traveler, UnchangeableObject, UndeletableObject, UnorderedObject, UserProxy, Villain, Vodcast, Whatsit, Widget, Worker, WorkHour, ) ERROR_MESSAGE = "Please enter the correct username and password \ for a staff account. Note that both fields may be case-sensitive." MULTIPART_ENCTYPE = 'enctype="multipart/form-data"' def make_aware_datetimes(dt, iana_key): """Makes one aware datetime for each supported time zone provider.""" yield dt.replace(tzinfo=zoneinfo.ZoneInfo(iana_key)) class AdminFieldExtractionMixin: """ Helper methods for extracting data from AdminForm. """ def get_admin_form_fields(self, response): """ Return a list of AdminFields for the AdminForm in the response. """ fields = [] for fieldset in response.context["adminform"]: for field_line in fieldset: fields.extend(field_line) return fields def get_admin_readonly_fields(self, response): """ Return the readonly fields for the response's AdminForm. """ return [f for f in self.get_admin_form_fields(response) if f.is_readonly] def get_admin_readonly_field(self, response, field_name): """ Return the readonly field for the given field_name. """ admin_readonly_fields = self.get_admin_readonly_fields(response) for field in admin_readonly_fields: if field.field["name"] == field_name: return field @override_settings(ROOT_URLCONF="admin_views.urls", USE_I18N=True, LANGUAGE_CODE="en") class AdminViewBasicTestCase(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="

Middle content

", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, title="Article 1", ) cls.a2 = Article.objects.create( content="

Oldest content

", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, title="Article 2", ) cls.a3 = Article.objects.create( content="

Newest content

", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.color1 = Color.objects.create(value="Red", warm=True) cls.color2 = Color.objects.create(value="Orange", warm=True) cls.color3 = Color.objects.create(value="Blue", warm=False) cls.color4 = Color.objects.create(value="Green", warm=False) cls.fab1 = Fabric.objects.create(surface="x") cls.fab2 = Fabric.objects.create(surface="y") cls.fab3 = Fabric.objects.create(surface="plain") cls.b1 = Book.objects.create(name="Book 1") cls.b2 = Book.objects.create(name="Book 2") cls.pro1 = Promo.objects.create(name="Promo 1", book=cls.b1) cls.pro1 = Promo.objects.create(name="Promo 2", book=cls.b2) cls.chap1 = Chapter.objects.create( title="Chapter 1", content="[ insert contents here ]", book=cls.b1 ) cls.chap2 = Chapter.objects.create( title="Chapter 2", content="[ insert contents here ]", book=cls.b1 ) cls.chap3 = Chapter.objects.create( title="Chapter 1", content="[ insert contents here ]", book=cls.b2 ) cls.chap4 = Chapter.objects.create( title="Chapter 2", content="[ insert contents here ]", book=cls.b2 ) cls.cx1 = ChapterXtra1.objects.create(chap=cls.chap1, xtra="ChapterXtra1 1") cls.cx2 = ChapterXtra1.objects.create(chap=cls.chap3, xtra="ChapterXtra1 2") Actor.objects.create(name="Palin", age=27) # Post data for edit inline cls.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": cls.a1.pk, # 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": cls.s1.pk, "article_set-1-id": cls.a2.pk, "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": cls.a3.pk, "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 setUp(self): self.client.force_login(self.superuser) 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.assertLess( response.content.index(text1.encode()), response.content.index(text2.encode()), (failing_msg or "") + "\nResponse:\n" + response.content.decode(response.charset), ) class AdminViewBasicTest(AdminViewBasicTestCase): def test_trailing_slash_required(self): """ If you leave off the trailing slash, app should redirect and add it. """ add_url = reverse("admin:admin_views_article_add") response = self.client.get(add_url[:-1]) self.assertRedirects(response, add_url, status_code=301) def test_basic_add_GET(self): """ A smoke test to ensure GET on the add_view works. """ response = self.client.get(reverse("admin:admin_views_section_add")) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_add_with_GET_args(self): response = self.client.get( reverse("admin:admin_views_section_add"), {"name": "My Section"} ) 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( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_basic_edit_GET_string_PK(self): """ GET on the change_view (when passing a string as the PK argument for a model with an integer PK field) redirects to the index page with a message saying the object doesn't exist. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(quote("abc/"),)), follow=True, ) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["section with ID “abc/” doesn’t exist. Perhaps it was deleted?"], ) def test_basic_edit_GET_old_url_redirect(self): """ The change URL changed in Django 1.9, but the old one still redirects. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)).replace( "change/", "" ) ) self.assertRedirects( response, reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) def test_basic_inheritance_GET_string_PK(self): """ GET on the change_view (for inherited models) redirects to the index page with a message saying the object doesn't exist. """ response = self.client.get( reverse("admin:admin_views_supervillain_change", args=("abc",)), follow=True ) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["super villain with ID “abc” doesn’t exist. Perhaps it was deleted?"], ) 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(reverse("admin:admin_views_section_add"), post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def test_popup_add_POST(self): """HTTP response from a popup is properly escaped.""" post_data = { IS_POPUP_VAR: "1", "title": "title with a new\nline", "content": "some content", "date_0": "2010-09-10", "date_1": "14:55:39", } response = self.client.post(reverse("admin:admin_views_article_add"), post_data) self.assertContains(response, "title with a new\\nline") def test_basic_edit_POST(self): """ A smoke test to ensure POST on edit_view works. """ url = reverse("admin:admin_views_section_change", args=(self.s1.pk,)) response = self.client.post(url, 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( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), post_data ) self.assertEqual(response.status_code, 302) # redirect somewhere def test_edit_save_as_delete_inline(self): """ Should be able to "Save as new" while also deleting an inline. """ 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-2-DELETE": "1", "article_set-3-section": "1", } ) response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), post_data ) self.assertEqual(response.status_code, 302) # started with 3 articles, one was deleted. self.assertEqual(Section.objects.latest("id").article_set.count(), 2) def test_change_list_column_field_classes(self): response = self.client.get(reverse("admin:admin_views_article_changelist")) # callables display the callable name. self.assertContains(response, "column-callable_year") self.assertContains(response, "field-callable_year") # lambdas display as "lambda" + index that they appear in list_display. self.assertContains(response, "column-lambda8") self.assertContains(response, "field-lambda8") 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( reverse("admin:admin_views_article_changelist"), {"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_boolean_display_property(self): response = self.client.get(reverse("admin:admin_views_article_changelist")) self.assertContains( response, '' 'True', ) def test_change_list_sorting_property(self): """ Sort on a list_display field that is a property (column 10 is a property in Article model). """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": 10} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on property are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on property are out of order.", ) def test_change_list_sorting_callable_query_expression(self): """Query expressions may be used for admin_order_field.""" tests = [ ("order_by_expression", 9), ("order_by_f_expression", 12), ("order_by_orderby_expression", 13), ] for admin_order_field, index in tests: with self.subTest(admin_order_field): response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": index}, ) 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_callable_query_expression_reverse(self): tests = [ ("order_by_expression", -9), ("order_by_f_expression", -12), ("order_by_orderby_expression", -13), ] for admin_order_field, index in tests: with self.subTest(admin_order_field): response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": index}, ) self.assertContentBefore( response, "Middle content", "Oldest content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Newest content", "Middle 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( reverse("admin:admin_views_article_changelist"), {"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( reverse("admin:admin_views_article_changelist"), {"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) """ td = '%s' td_2000, td_2008, td_2009 = td % 2000, td % 2008, td % 2009 response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "6"} ) self.assertContentBefore( response, td_2009, td_2008, "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, td_2008, td_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( reverse("admin:admin_views_article_changelist"), {"o": "-6"} ) self.assertContentBefore( response, td_2000, td_2008, "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, td_2008, td_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 response = self.client.get( reverse("admin:admin_views_person_changelist"), {"o": "1.2"} ) self.assertContentBefore(response, link3, link1) self.assertContentBefore(response, link1, link2) # Sort by gender descending, name response = self.client.get( reverse("admin:admin_views_person_changelist"), {"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,)) response = self.client.get(reverse("admin:admin_views_person_changelist"), {}) 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(reverse("admin:admin_views_language_changelist"), {}) self.assertContentBefore(response, link2, link1) # Test we can override with query string response = self.client.get( reverse("admin:admin_views_language_changelist"), {"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(reverse("admin:admin_views_podcast_changelist"), {}) self.assertContentBefore(response, link1, link2) def test_multiple_sort_same_field(self): # The changelist displays the correct columns if two columns 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(reverse("admin:admin_views_podcast_changelist"), {}) 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( reverse("admin:admin_views_complexsortedperson_changelist"), {} ) # Should have 5 columns (including action checkbox col) self.assertContains(response, '_id fields in list display.""" state = State.objects.create(name="Karnataka") City.objects.create(state=state, name="Bangalore") response = self.client.get(reverse("admin:admin_views_city_changelist"), {}) response.context["cl"].list_display = ["id", "name", "state"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), True) response.context["cl"].list_display = ["id", "name", "state_id"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), False) def test_has_related_field_in_list_display_o2o(self): """Joins shouldn't be performed for _id fields in list display.""" media = Media.objects.create(name="Foo") Vodcast.objects.create(media=media) response = self.client.get(reverse("admin:admin_views_vodcast_changelist"), {}) response.context["cl"].list_display = ["media"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), True) response.context["cl"].list_display = ["media_id"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), False) def test_limited_filter(self): """ Admin changelist filters do not contain objects excluded via limit_choices_to. """ response = self.client.get(reverse("admin:admin_views_thing_changelist")) 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_change_list_facet_toggle(self): # Toggle is visible when show_facet is the default of # admin.ShowFacets.ALLOW. admin_url = reverse("admin:admin_views_album_changelist") response = self.client.get(admin_url) self.assertContains( response, 'Show counts', msg_prefix="Expected facet filter toggle not found in changelist view", ) response = self.client.get(f"{admin_url}?_facets=True") self.assertContains( response, 'Hide counts', msg_prefix="Expected facet filter toggle not found in changelist view", ) # Toggle is not visible when show_facet is admin.ShowFacets.ALWAYS. response = self.client.get(reverse("admin:admin_views_workhour_changelist")) self.assertNotContains( response, "Show counts", msg_prefix="Expected not to find facet filter toggle in changelist view", ) self.assertNotContains( response, "Hide counts", msg_prefix="Expected not to find facet filter toggle in changelist view", ) # Toggle is not visible when show_facet is admin.ShowFacets.NEVER. response = self.client.get(reverse("admin:admin_views_fooddelivery_changelist")) self.assertNotContains( response, "Show counts", msg_prefix="Expected not to find facet filter toggle in changelist view", ) self.assertNotContains( response, "Hide counts", msg_prefix="Expected not to find facet filter toggle in changelist view", ) def test_relation_spanning_filters(self): changelist_url = reverse("admin:admin_views_chapterxtra1_changelist") response = self.client.get(changelist_url) self.assertContains(response, '
') filters = { "chap__id__exact": { "values": [c.id for c in Chapter.objects.all()], "test": lambda obj, value: obj.chap.id == value, }, "chap__title": { "values": [c.title for c in Chapter.objects.all()], "test": lambda obj, value: obj.chap.title == value, }, "chap__book__id__exact": { "values": [b.id for b in Book.objects.all()], "test": lambda obj, value: obj.chap.book.id == value, }, "chap__book__name": { "values": [b.name for b in Book.objects.all()], "test": lambda obj, value: obj.chap.book.name == value, }, "chap__book__promo__id__exact": { "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": { "values": [p.name for p in Promo.objects.all()], "test": lambda obj, value: obj.chap.book.promo_set.filter( name=value ).exists(), }, # A forward relation (book) after a reverse relation (promo). "guest_author__promo__book__id__exact": { "values": [p.id for p in Book.objects.all()], "test": lambda obj, value: obj.guest_author.promo_set.filter( book=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, '' % reverse("admin:logout"), ) self.assertContains( response, '' % reverse("admin:password_change") ) 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=(self.fab1.pk,)) link2 = reverse("admin:admin_views_fabric_change", args=(self.fab2.pk,)) response = self.client.get(reverse("admin:admin_views_fabric_changelist")) 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(reverse("admin:admin_views_fabric_changelist")) 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) response = self.client.get(reverse("admin:admin_views_post_changelist")) self.assertContains(response, "icon-unknown.svg") def test_display_decorator_with_boolean_and_empty_value(self): msg = ( "The boolean and empty_value arguments to the @display decorator " "are mutually exclusive." ) with self.assertRaisesMessage(ValueError, msg): class BookAdmin(admin.ModelAdmin): @admin.display(boolean=True, empty_value="(Missing)") def is_published(self, obj): return obj.publish_date is not None 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(reverse("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(reverse("admin:jsi18n")) self.assertContains(response, "Choisir une heure") def test_jsi18n_with_context(self): response = self.client.get(reverse("admin-extra-context:jsi18n")) self.assertEqual(response.status_code, 200) def test_jsi18n_format_fallback(self): """ The JavaScript i18n view doesn't return localized date/time formats when the selected language cannot be found. """ with self.settings(LANGUAGE_CODE="ru"), translation.override("none"): response = self.client.get(reverse("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 self.assertLogs("django.security.DisallowedModelAdminLookup", "ERROR"): response = self.client.get( "%s?owner__email__startswith=fuzzy" % reverse("admin:admin_views_album_changelist") ) self.assertEqual(response.status_code, 400) # Filters are allowed if explicitly included in list_filter response = self.client.get( "%s?color__value__startswith=red" % reverse("admin:admin_views_thing_changelist") ) self.assertEqual(response.status_code, 200) response = self.client.get( "%s?color__value=red" % reverse("admin:admin_views_thing_changelist") ) self.assertEqual(response.status_code, 200) # Filters should be allowed if they involve a local field without the # need to allow them in list_filter or date_hierarchy. response = self.client.get( "%s?age__gt=30" % reverse("admin:admin_views_person_changelist") ) 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(reverse("admin:admin_views_workhour_changelist")) self.assertContains(response, "employee__person_ptr__exact") response = self.client.get( "%s?employee__person_ptr__exact=%d" % (reverse("admin:admin_views_workhour_changelist"), e1.pk) ) self.assertEqual(response.status_code, 200) def test_disallowed_to_field(self): url = reverse("admin:admin_views_section_changelist") with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.get(url, {TO_FIELD_VAR: "missing_field"}) self.assertEqual(response.status_code, 400) # Specifying a field that is not referred by any other model registered # to this admin site should raise an exception. with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.get( reverse("admin:admin_views_section_changelist"), {TO_FIELD_VAR: "name"} ) self.assertEqual(response.status_code, 400) # Primary key should always be allowed, even if the referenced model # isn't registered. response = self.client.get( reverse("admin:admin_views_notreferenced_changelist"), {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( reverse("admin:admin_views_recipe_changelist"), {TO_FIELD_VAR: "rname"} ) self.assertEqual(response.status_code, 200) # Specifying a field referenced through a reverse m2m relationship # should be allowed. response = self.client.get( reverse("admin:admin_views_ingredient_changelist"), {TO_FIELD_VAR: "iname"} ) self.assertEqual(response.status_code, 200) # Specifying a field that is not referred by any other model directly # registered to this admin site but registered through inheritance # should be allowed. response = self.client.get( reverse("admin:admin_views_referencedbyparent_changelist"), {TO_FIELD_VAR: "name"}, ) self.assertEqual(response.status_code, 200) # Specifying a field that is only referred to by a inline of a # registered model should be allowed. response = self.client.get( reverse("admin:admin_views_referencedbyinline_changelist"), {TO_FIELD_VAR: "name"}, ) self.assertEqual(response.status_code, 200) # #25622 - Specifying a field of a model only referred by a generic # relation should raise DisallowedModelAdminToField. url = reverse("admin:admin_views_referencedbygenrel_changelist") with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.get(url, {TO_FIELD_VAR: "object_id"}) self.assertEqual(response.status_code, 400) # We also want to prevent the add, change, and delete views from # leaking a disallowed field value. with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.post( reverse("admin:admin_views_section_add"), {TO_FIELD_VAR: "name"} ) self.assertEqual(response.status_code, 400) section = Section.objects.create() url = reverse("admin:admin_views_section_change", args=(section.pk,)) with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.post(url, {TO_FIELD_VAR: "name"}) self.assertEqual(response.status_code, 400) url = reverse("admin:admin_views_section_delete", args=(section.pk,)) with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.post(url, {TO_FIELD_VAR: "name"}) self.assertEqual(response.status_code, 400) 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. url = "%s?leader__name=Palin&leader__age=27" % reverse( "admin:admin_views_inquisition_changelist" ) response = self.client.get(url) 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( "%s?%s" % (reverse("admin:admin_views_actor_changelist"), IS_POPUP_VAR) ) self.assertContains(response, 'data-popup-opener="%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() self.client.force_login(user) response = self.client.get(reverse("admin:index")) 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): """ The 'show_delete' context variable in the admin's change view controls the display of the delete button. """ instance = UndeletableObject.objects.create(name="foo") response = self.client.get( reverse("admin:admin_views_undeletableobject_change", args=(instance.pk,)) ) self.assertNotContains(response, "deletelink") def test_change_view_logs_m2m_field_changes(self): """Changes to ManyToManyFields are included in the object's history.""" pizza = ReadablePizza.objects.create(name="Cheese") cheese = Topping.objects.create(name="cheese") post_data = {"name": pizza.name, "toppings": [cheese.pk]} response = self.client.post( reverse("admin:admin_views_readablepizza_change", args=(pizza.pk,)), post_data, ) self.assertRedirects( response, reverse("admin:admin_views_readablepizza_changelist") ) pizza_ctype = ContentType.objects.get_for_model( ReadablePizza, for_concrete_model=False ) log = LogEntry.objects.filter( content_type=pizza_ctype, object_id=pizza.pk ).first() self.assertEqual(log.get_change_message(), "Changed Toppings.") def test_allows_attributeerror_to_bubble_up(self): """ AttributeErrors are allowed to bubble when raised inside a change list view. Requires a model to be created so there's something to display. Refs: #16655, #18593, and #18747 """ Simple.objects.create() with self.assertRaises(AttributeError): self.client.get(reverse("admin:admin_views_simple_changelist")) 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 (#20934). """ o = UnchangeableObject.objects.create() response = self.client.get( reverse("admin:admin_views_unchangeableobject_changelist") ) # Check the format of the shown object -- shouldn't contain a change link self.assertContains( response, '%s' % o, 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_resolve_admin_views(self): index_match = resolve("/test_admin/admin4/") list_match = resolve("/test_admin/admin4/auth/user/") self.assertIs(index_match.func.admin_site, customadmin.simple_site) self.assertIsInstance( list_match.func.model_admin, customadmin.CustomPwdTemplateUserAdmin ) 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') def test_date_hierarchy_empty_queryset(self): self.assertIs(Question.objects.exists(), False) response = self.client.get(reverse("admin:admin_views_answer2_changelist")) self.assertEqual(response.status_code, 200) @override_settings(TIME_ZONE="America/Sao_Paulo", USE_TZ=True) def test_date_hierarchy_timezone_dst(self): # This datetime doesn't exist in this timezone due to DST. for date in make_aware_datetimes( datetime.datetime(2016, 10, 16, 15), "America/Sao_Paulo" ): with self.subTest(repr(date.tzinfo)): q = Question.objects.create(question="Why?", expires=date) Answer2.objects.create(question=q, answer="Because.") response = self.client.get( reverse("admin:admin_views_answer2_changelist") ) self.assertContains(response, "question__expires__day=16") self.assertContains(response, "question__expires__month=10") self.assertContains(response, "question__expires__year=2016") @override_settings(TIME_ZONE="America/Los_Angeles", USE_TZ=True) def test_date_hierarchy_local_date_differ_from_utc(self): # This datetime is 2017-01-01 in UTC. for date in make_aware_datetimes( datetime.datetime(2016, 12, 31, 16), "America/Los_Angeles" ): with self.subTest(repr(date.tzinfo)): q = Question.objects.create(question="Why?", expires=date) Answer2.objects.create(question=q, answer="Because.") response = self.client.get( reverse("admin:admin_views_answer2_changelist") ) self.assertContains(response, "question__expires__day=31") self.assertContains(response, "question__expires__month=12") self.assertContains(response, "question__expires__year=2016") def test_sortable_by_columns_subset(self): expected_sortable_fields = ("date", "callable_year") expected_not_sortable_fields = ( "content", "model_year", "modeladmin_year", "model_year_reversed", "section", ) response = self.client.get(reverse("admin6:admin_views_article_changelist")) for field_name in expected_sortable_fields: self.assertContains( response, '' % field_name ) for field_name in expected_not_sortable_fields: self.assertContains( response, '' % field_name ) def test_get_sortable_by_columns_subset(self): response = self.client.get(reverse("admin6:admin_views_actor_changelist")) self.assertContains(response, '') self.assertContains(response, '') def test_sortable_by_no_column(self): expected_not_sortable_fields = ("title", "book") response = self.client.get(reverse("admin6:admin_views_chapter_changelist")) for field_name in expected_not_sortable_fields: self.assertContains( response, '' % field_name ) self.assertNotContains(response, '') self.assertNotContains(response, 'Admin_Views administration | Django site admin", ) self.assertEqual(response.context["title"], "Admin_Views administration") self.assertEqual(response.context["app_label"], "admin_views") # Models are sorted alphabetically by default. models = [model["name"] for model in response.context["app_list"][0]["models"]] self.assertSequenceEqual(models, sorted(models)) def test_app_index_context_reordered(self): self.client.force_login(self.superuser) response = self.client.get(reverse("admin2:app_list", args=("admin_views",))) self.assertContains( response, "Admin_Views administration | Django site admin", ) # Models are in reverse order. models = [model["name"] for model in response.context["app_list"][0]["models"]] self.assertSequenceEqual(models, sorted(models, reverse=True)) def test_change_view_subtitle_per_object(self): response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a1.pk,)), ) self.assertContains( response, "Article 1 | Change article | Django site admin", ) self.assertContains(response, "

Change article

") self.assertContains(response, "

Article 1

") response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a2.pk,)), ) self.assertContains( response, "Article 2 | Change article | Django site admin", ) self.assertContains(response, "

Change article

") self.assertContains(response, "

Article 2

") def test_view_subtitle_per_object(self): viewuser = User.objects.create_user( username="viewuser", password="secret", is_staff=True, ) viewuser.user_permissions.add( get_perm(Article, get_permission_codename("view", Article._meta)), ) self.client.force_login(viewuser) response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a1.pk,)), ) self.assertContains( response, "Article 1 | View article | Django site admin", ) self.assertContains(response, "

View article

") self.assertContains(response, "

Article 1

") response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a2.pk,)), ) self.assertContains( response, "Article 2 | View article | Django site admin", ) self.assertContains(response, "

View article

") self.assertContains(response, "

Article 2

") def test_formset_kwargs_can_be_overridden(self): response = self.client.get(reverse("admin:admin_views_city_add")) self.assertContains(response, "overridden_name") def test_render_views_no_subtitle(self): tests = [ reverse("admin:index"), reverse("admin:password_change"), reverse("admin:app_list", args=("admin_views",)), reverse("admin:admin_views_article_delete", args=(self.a1.pk,)), reverse("admin:admin_views_article_history", args=(self.a1.pk,)), ] for url in tests: with self.subTest(url=url): with self.assertNoLogs("django.template", "DEBUG"): self.client.get(url) # Login must be after logout. with self.assertNoLogs("django.template", "DEBUG"): self.client.post(reverse("admin:logout")) self.client.get(reverse("admin:login")) def test_render_delete_selected_confirmation_no_subtitle(self): post_data = { "action": "delete_selected", "selected_across": "0", "index": "0", "_selected_action": self.a1.pk, } with self.assertNoLogs("django.template", "DEBUG"): self.client.post(reverse("admin:admin_views_article_changelist"), post_data) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, { "NAME": ( "django.contrib.auth.password_validation." "NumericPasswordValidator" ) }, ] ) def test_password_change_helptext(self): response = self.client.get(reverse("admin:password_change")) self.assertContains( response, '
' ) def test_enable_zooming_on_mobile(self): response = self.client.get(reverse("admin:index")) self.assertContains( response, '', ) def test_header(self): response = self.client.get(reverse("admin:index")) self.assertContains(response, '