import datetime import os import re import sys import unittest import zoneinfo from http import HTTPStatus from unittest import mock from urllib.parse import parse_qsl, urljoin, urlsplit 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 SOURCE_MODEL_VAR, 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.models.utils import get_blank_choice_label from django.forms.utils import ErrorList from django.template.response import TemplateResponse from django.test import ( RequestFactory, TestCase, modify_settings, override_settings, skipUnlessDBFeature, ) from django.test.selenium import screenshot_cases 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.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, Country, Course, 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, Subscriber, SuperSecretHideout, SuperVillain, Telegram, TitleTranslation, Topping, Traveler, UnchangeableObject, UndeletableObject, UnorderedObject, UserMessenger, 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.text, ) 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_add_query_string_persists(self): save_options = [ {"_addanother": "1"}, # "Save and add another". {"_continue": "1"}, # "Save and continue editing". {"_saveasnew": "1"}, # "Save as new". ] other_options = [ "", "_changelist_filters=is_staff__exact%3D0", f"{IS_POPUP_VAR}=1", f"{TO_FIELD_VAR}=id", ] url = reverse("admin:auth_user_add") for i, save_option in enumerate(save_options): for j, other_option in enumerate(other_options): with self.subTest(save_option=save_option, other_option=other_option): qsl = "username=newuser" if other_option: qsl = f"{qsl}&{other_option}" response = self.client.post( f"{url}?{qsl}", { "username": f"newuser{i}{j}", "password1": "newpassword", "password2": "newpassword", **save_option, }, ) parsed_url = urlsplit(response.url) self.assertEqual(parsed_url.query, qsl) def test_change_query_string_persists(self): save_options = [ {"_addanother": "1"}, # "Save and add another". {"_continue": "1"}, # "Save and continue editing". ] other_options = [ "", "_changelist_filters=warm%3D1", f"{IS_POPUP_VAR}=1", f"{TO_FIELD_VAR}=id", ] url = reverse("admin:admin_views_color_change", args=(self.color1.pk,)) for save_option in save_options: for other_option in other_options: with self.subTest(save_option=save_option, other_option=other_option): qsl = "value=blue" if other_option: qsl = f"{qsl}&{other_option}" response = self.client.post( f"{url}?{qsl}", { "value": "gold", "warm": True, **save_option, }, ) parsed_url = urlsplit(response.url) self.assertEqual(parsed_url.query, qsl) 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_popup_add_POST_with_valid_source_model(self): """ Popup add with a valid source_model returns a successful response. """ post_data = { IS_POPUP_VAR: "1", SOURCE_MODEL_VAR: "admin_views.section", "title": "Test Article", "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.assertEqual(response.status_code, 200) self.assertContains(response, "data-popup-response") messages = list(response.wsgi_request._messages) self.assertEqual(len(messages), 0) def test_popup_add_POST_with_optgroups(self): """ Popup add with source_model containing optgroup choices includes the optgroup in the response. """ post_data = { IS_POPUP_VAR: "1", SOURCE_MODEL_VAR: "admin_views.section", "title": "Test Article", "content": "some content", "date_0": "2010-09-10", "date_1": "14:55:39", } response = self.client.post( reverse("admin11:admin_views_article_add"), post_data ) self.assertEqual(response.status_code, 200) self.assertContains(response, ""optgroup": "Published"") def test_popup_add_POST_without_optgroups(self): """ Popup add where source_model form exists but doesn't have the field should work without crashing. """ post_data = { IS_POPUP_VAR: "1", SOURCE_MODEL_VAR: "admin_views.section", "title": "Test Article 2", "content": "some content", "date_0": "2010-09-10", "date_1": "14:55:39", } # Use regular admin (not admin11) where Section doesn't have optgroups. response = self.client.post(reverse("admin:admin_views_article_add"), post_data) self.assertEqual(response.status_code, 200) self.assertContains(response, "data-popup-response") self.assertNotContains(response, ""optgroup"") def test_popup_add_POST_with_object_optgroups(self): """ Popup add with source_model containing optgroups where the optgroup keys are model instances (not strings) still serialize to strings. """ post_data = { IS_POPUP_VAR: "1", SOURCE_MODEL_VAR: "admin_views.section", "title": "Article 1", "content": "some content", "date_0": "2010-09-10", "date_1": "14:55:39", } response = self.client.post( reverse("admin12:admin_views_article_add"), post_data ) self.assertEqual(response.status_code, 200) # Check that optgroup is in the response with str() of Section instance # The form uses Section.objects.all()[:2] which includes cls.s1 # ("Test section") as the first optgroup key (HTML encoded). self.assertContains(response, ""optgroup": "Test section"") def test_popup_add_POST_with_dynamic_optgroups(self): """ Popup add with source_model where optgroup field is added dynamically in __init__. This ensures the implementation doesn't rely on accessing the uninstantiated form class's _meta or fields, but instead properly instantiates the form with get_form(request)() to access field info. """ post_data = { IS_POPUP_VAR: "1", SOURCE_MODEL_VAR: "admin_views.section", "title": "Item 1", "content": "some content", "date_0": "2010-09-10", "date_1": "14:55:39", } response = self.client.post( reverse("admin13:admin_views_article_add"), post_data ) self.assertEqual(response.status_code, 200) self.assertContains(response, ""optgroup": "Category A"") def test_popup_add_POST_with_invalid_source_model(self): """ Popup add with an invalid source_model (non-existent app/model) shows an error message instead of crashing. """ post_data = { IS_POPUP_VAR: "1", SOURCE_MODEL_VAR: "admin_views.nonexistent", "title": "Test Article", "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.assertEqual(response.status_code, 200) self.assertContains(response, "data-popup-response") messages = list(response.wsgi_request._messages) self.assertEqual(len(messages), 1) self.assertIn("admin_views.nonexistent", str(messages[0])) self.assertIn("could not be found", str(messages[0])) def test_popup_add_POST_with_unregistered_source_model(self): """ Popup add where source_model is a valid Django model but is not registered in the admin site (e.g. a model only used as an inline) should succeed without raising a KeyError. """ post_data = { IS_POPUP_VAR: "1", # Chapter exists as a model but is not registered in site (only # in site6), simulating a model used only as an inline. SOURCE_MODEL_VAR: "admin_views.chapter", "title": "Test Article", "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.assertEqual(response.status_code, 200) self.assertContains(response, "data-popup-response") # No error messages - unregistered model is silently skipped. messages = list(response.wsgi_request._messages) self.assertEqual(len(messages), 0) # No optgroup in the response. self.assertNotContains(response, ""optgroup"") 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, '| (.*?)') result_list_table_head = result_list_table_re.search(str(response.content))[ 0 ] self.assertEqual(result_list_table_head.count(' | _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 | %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,
" | Change article") self.assertContains(response, "Article 1") response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a2.pk,)), ) self.assertContains( response, "Change article") self.assertContains(response, "Article 2") def test_error_in_titles(self): for url, subtitle in [ ( reverse("admin:admin_views_article_change", args=(self.a1.pk,)), "Article 1 | Change article", ), (reverse("admin:admin_views_article_add"), "Add article"), (reverse("admin:login"), "Log in"), (reverse("admin:password_change"), "Password change"), ( reverse("admin:auth_user_password_change", args=(self.superuser.id,)), "Change password: super", ), ]: with self.subTest(url=url, subtitle=subtitle): response = self.client.post(url, {}) self.assertContains(response, f"View article") self.assertContains(response, "Article 1") response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a2.pk,)), ) 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, ' |
|---|