import datetime import os import re import unittest from unittest import mock from urllib.parse import parse_qsl, urljoin, urlparse try: import zoneinfo except ImportError: from backports import zoneinfo try: import pytz except ImportError: pytz = None 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.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 ( TestCase, 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.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)) if pytz is not None: yield pytz.timezone(iana_key).localize(dt, is_dst=None) 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_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 = 'great article
", "date_0": "2008-03-18", "date_1": "10:54:39", }, ) self.assertRedirects( post, reverse("admin:admin_views_customarticle_changelist") ) self.assertEqual(CustomArticle.objects.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( reverse("admin:admin_views_customarticle_change", args=(article_pk,)) ) self.assertTemplateUsed(response, "custom_admin/change_form.html") response = self.client.get( reverse("admin:admin_views_customarticle_delete", args=(article_pk,)) ) self.assertTemplateUsed(response, "custom_admin/delete_confirmation.html") response = self.client.post( reverse("admin:admin_views_customarticle_changelist"), data={ "index": 0, "action": ["delete_selected"], "_selected_action": ["1"], }, ) self.assertTemplateUsed( response, "custom_admin/delete_selected_confirmation.html" ) response = self.client.get( reverse("admin:admin_views_customarticle_history", args=(article_pk,)) ) self.assertTemplateUsed(response, "custom_admin/object_history.html") # A custom popup response template may be specified by # ModelAdmin.popup_response_template. response = self.client.post( reverse("admin:admin_views_customarticle_add") + "?%s=1" % IS_POPUP_VAR, { "content": "great article
", "date_0": "2008-03-18", "date_1": "10:54:39", IS_POPUP_VAR: "1", }, ) self.assertEqual(response.template_name, "custom_admin/popup_response.html") def test_extended_bodyclass_template_change_form(self): """ The admin/change_form.html template uses block.super in the bodyclass block. """ response = self.client.get(reverse("admin:admin_views_section_add")) self.assertContains(response, "bodyclass_consistency_check ") def test_change_password_template(self): user = User.objects.get(username="super") response = self.client.get( reverse("admin:auth_user_password_change", args=(user.id,)) ) # The auth/user/change_password.html template uses super in the # bodyclass block. self.assertContains(response, "bodyclass_consistency_check ") # When a site has multiple passwords in the browser's password manager, # a browser pop up asks which user the new password is for. To prevent # this, the username is added to the change password form. self.assertContains( response, '' ) # help text for passwords has an id. self.assertContains( response, 'Middle content
", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="Oldest content
", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) 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" ) def setUp(self): self.client.force_login(self.superuser) def test_change_form_URL_has_correct_value(self): """ change_view has form_url in response.context """ response = self.client.get( reverse( "admin:admin_views_section_change", args=(self.s1.pk,), current_app=self.current_app, ) ) self.assertIn( "form_url", 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): """ 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( reverse("admin:admin_views_restaurant_add", current_app=self.current_app), {"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(ROOT_URLCONF="admin_views.urls") class AdminJavaScriptTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) def setUp(self): self.client.force_login(self.superuser) def test_js_minified_only_if_debug_is_false(self): """ The minified versions of the JS files are only used when DEBUG is False. """ with override_settings(DEBUG=False): response = self.client.get(reverse("admin:admin_views_section_add")) self.assertNotContains(response, "vendor/jquery/jquery.js") self.assertContains(response, "vendor/jquery/jquery.min.js") self.assertContains(response, "prepopulate.js") self.assertContains(response, "actions.js") self.assertContains(response, "collapse.js") self.assertContains(response, "inlines.js") with override_settings(DEBUG=True): response = self.client.get(reverse("admin:admin_views_section_add")) self.assertContains(response, "vendor/jquery/jquery.js") self.assertNotContains(response, "vendor/jquery/jquery.min.js") self.assertContains(response, "prepopulate.js") self.assertContains(response, "actions.js") self.assertContains(response, "collapse.js") self.assertContains(response, "inlines.js") @override_settings(ROOT_URLCONF="admin_views.urls") class SaveAsTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) def setUp(self): self.client.force_login(self.superuser) def test_save_as_duplication(self): """'save as' creates a new person""" post_data = {"_saveasnew": "", "name": "John M", "gender": 1, "age": 42} response = self.client.post( reverse("admin:admin_views_person_change", args=(self.per1.pk,)), post_data ) self.assertEqual(len(Person.objects.filter(name="John M")), 1) self.assertEqual(len(Person.objects.filter(id=self.per1.pk)), 1) new_person = Person.objects.latest("id") self.assertRedirects( response, reverse("admin:admin_views_person_change", args=(new_person.pk,)) ) def test_save_as_continue_false(self): """ Saving a new object using "Save as new" redirects to the changelist instead of the change view when ModelAdmin.save_as_continue=False. """ post_data = {"_saveasnew": "", "name": "John M", "gender": 1, "age": 42} url = reverse( "admin:admin_views_person_change", args=(self.per1.pk,), current_app=site2.name, ) response = self.client.post(url, post_data) self.assertEqual(len(Person.objects.filter(name="John M")), 1) self.assertEqual(len(Person.objects.filter(id=self.per1.pk)), 1) self.assertRedirects( response, reverse("admin:admin_views_person_changelist", current_app=site2.name), ) def test_save_as_new_with_validation_errors(self): """ When you click "Save as new" and have a validation error, you only see the "Save as new" button and not the other save buttons, and that only the "Save as" button is visible. """ response = self.client.post( reverse("admin:admin_views_person_change", args=(self.per1.pk,)), { "_saveasnew": "", "gender": "invalid", "_addanother": "fail", }, ) self.assertContains(response, "Please correct the errors below.") self.assertFalse(response.context["show_save_and_add_another"]) self.assertFalse(response.context["show_save_and_continue"]) self.assertTrue(response.context["show_save_as_new"]) def test_save_as_new_with_validation_errors_with_inlines(self): parent = Parent.objects.create(name="Father") child = Child.objects.create(parent=parent, name="Child") response = self.client.post( reverse("admin:admin_views_parent_change", args=(parent.pk,)), { "_saveasnew": "Save as new", "child_set-0-parent": parent.pk, "child_set-0-id": child.pk, "child_set-0-name": "Child", "child_set-INITIAL_FORMS": 1, "child_set-MAX_NUM_FORMS": 1000, "child_set-MIN_NUM_FORMS": 0, "child_set-TOTAL_FORMS": 4, "name": "_invalid", }, ) self.assertContains(response, "Please correct the error below.") self.assertFalse(response.context["show_save_and_add_another"]) self.assertFalse(response.context["show_save_and_continue"]) self.assertTrue(response.context["show_save_as_new"]) def test_save_as_new_with_inlines_with_validation_errors(self): parent = Parent.objects.create(name="Father") child = Child.objects.create(parent=parent, name="Child") response = self.client.post( reverse("admin:admin_views_parent_change", args=(parent.pk,)), { "_saveasnew": "Save as new", "child_set-0-parent": parent.pk, "child_set-0-id": child.pk, "child_set-0-name": "_invalid", "child_set-INITIAL_FORMS": 1, "child_set-MAX_NUM_FORMS": 1000, "child_set-MIN_NUM_FORMS": 0, "child_set-TOTAL_FORMS": 4, "name": "Father", }, ) self.assertContains(response, "Please correct the error below.") self.assertFalse(response.context["show_save_and_add_another"]) self.assertFalse(response.context["show_save_and_continue"]) self.assertTrue(response.context["show_save_as_new"]) @override_settings(ROOT_URLCONF="admin_views.urls") class CustomModelAdminTest(AdminViewBasicTestCase): def test_custom_admin_site_login_form(self): self.client.logout() response = self.client.get(reverse("admin2:index"), follow=True) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) login = self.client.post( reverse("admin2:login"), { REDIRECT_FIELD_NAME: reverse("admin2:index"), "username": "customform", "password": "secret", }, follow=True, ) self.assertIsInstance(login, TemplateResponse) self.assertContains(login, "custom form error") self.assertContains(login, "path/to/media.css") def test_custom_admin_site_login_template(self): self.client.logout() response = self.client.get(reverse("admin2:index"), 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.post(reverse("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): response = self.client.get(reverse("admin2:index")) 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(reverse("admin2:app_list", args=("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(reverse("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_with_extra_context(self): response = self.client.get(reverse("admin2:password_change")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/password_change_form.html") self.assertContains(response, "eggs") def test_custom_admin_site_password_change_done_template(self): response = self.client.get(reverse("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.force_login(self.superuser) response = self.client.get(reverse("admin2:my_view")) self.assertEqual(response.content, b"Django is a magical pony!") def test_pwd_change_custom_template(self): self.client.force_login(self.superuser) su = User.objects.get(username="super") response = self.client.get( reverse("admin4:auth_user_password_change", args=(su.pk,)) ) self.assertEqual(response.status_code, 200) def get_perm(Model, codename): """Return the permission object, for the Model""" ct = ContentType.objects.get_for_model(Model, for_concrete_model=False) return Permission.objects.get(content_type=ct, codename=codename) @override_settings( ROOT_URLCONF="admin_views.urls", # Test with the admin's documented list of required context processors. TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ], ) class AdminViewPermissionsTest(TestCase): """Tests for Admin Views Permissions.""" @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) cls.viewuser = User.objects.create_user( username="viewuser", password="secret", is_staff=True ) cls.adduser = User.objects.create_user( username="adduser", password="secret", is_staff=True ) cls.changeuser = User.objects.create_user( username="changeuser", password="secret", is_staff=True ) cls.deleteuser = User.objects.create_user( username="deleteuser", password="secret", is_staff=True ) cls.joepublicuser = User.objects.create_user( username="joepublic", password="secret" ) cls.nostaffuser = User.objects.create_user( username="nostaff", password="secret" ) 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, another_section=cls.s1, ) cls.a2 = Article.objects.create( content="Oldest content
", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) 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" ) # Setup permissions, for our users who can add, change, and delete. opts = Article._meta # User who can view Articles cls.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("view", opts)) ) # User who can add Articles cls.adduser.user_permissions.add( get_perm(Article, get_permission_codename("add", opts)) ) # User who can change Articles cls.changeuser.user_permissions.add( get_perm(Article, get_permission_codename("change", opts)) ) cls.nostaffuser.user_permissions.add( get_perm(Article, get_permission_codename("change", opts)) ) # User who can delete Articles cls.deleteuser.user_permissions.add( get_perm(Article, get_permission_codename("delete", opts)) ) cls.deleteuser.user_permissions.add( get_perm(Section, get_permission_codename("delete", Section._meta)) ) # login POST dicts cls.index_url = reverse("admin:index") cls.super_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "super", "password": "secret", } cls.super_email_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "super@example.com", "password": "secret", } cls.super_email_bad_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "super@example.com", "password": "notsecret", } cls.adduser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "adduser", "password": "secret", } cls.changeuser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "changeuser", "password": "secret", } cls.deleteuser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "deleteuser", "password": "secret", } cls.nostaff_login = { REDIRECT_FIELD_NAME: reverse("has_permission_admin:index"), "username": "nostaff", "password": "secret", } cls.joepublic_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "joepublic", "password": "secret", } cls.viewuser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "viewuser", "password": "secret", } cls.no_username_login = { REDIRECT_FIELD_NAME: cls.index_url, "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 = "%s?next=%s" % (reverse("admin:login"), reverse("admin:index")) # Super User response = self.client.get(self.index_url) self.assertRedirects(response, login_url) login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Test if user enters email address response = self.client.get(self.index_url) 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) # View User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.viewuser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Add User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.adduser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Change User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.changeuser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Delete User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.deleteuser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Regular User should not be able to login. response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.joepublic_login) self.assertContains(login, ERROR_MESSAGE) # Requests without username should not return 500 errors. response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.no_username_login) self.assertEqual(login.status_code, 200) self.assertFormError( login.context["form"], "username", ["This field is required."] ) def test_login_redirect_for_direct_get(self): """ Login redirect should be to the admin index page when going directly to /admin/login/. """ response = self.client.get(reverse("admin:login")) self.assertEqual(response.status_code, 200) self.assertEqual(response.context[REDIRECT_FIELD_NAME], reverse("admin:index")) def test_login_has_permission(self): # Regular User should not be able to login. response = self.client.get(reverse("has_permission_admin:index")) self.assertEqual(response.status_code, 302) login = self.client.post( reverse("has_permission_admin:login"), self.joepublic_login ) self.assertContains(login, "permission denied") # User with permissions should be able to login. response = self.client.get(reverse("has_permission_admin:index")) self.assertEqual(response.status_code, 302) login = self.client.post( reverse("has_permission_admin:login"), self.nostaff_login ) self.assertRedirects(login, reverse("has_permission_admin:index")) self.assertFalse(login.context) self.client.post(reverse("has_permission_admin:logout")) # Staff should be able to login. response = self.client.get(reverse("has_permission_admin:index")) self.assertEqual(response.status_code, 302) login = self.client.post( reverse("has_permission_admin:login"), { REDIRECT_FIELD_NAME: reverse("has_permission_admin:index"), "username": "deleteuser", "password": "secret", }, ) self.assertRedirects(login, reverse("has_permission_admin:index")) self.assertFalse(login.context) self.client.post(reverse("has_permission_admin:logout")) def test_login_successfully_redirects_to_original_URL(self): response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) query_string = "the-answer=42" redirect_url = "%s?%s" % (self.index_url, 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 = "%s?next=%s" % (reverse("admin:login"), reverse("admin:index")) response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) # Establish a valid admin session login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) # Logging in with non-admin user fails login = self.client.post(login_url, self.joepublic_login) self.assertContains(login, ERROR_MESSAGE) # Establish a valid admin session login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) 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, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) def test_login_page_notice_for_non_staff_users(self): """ A logged-in non-staff user trying to access the admin index should be presented with the login page and a hint indicating that the current user doesn't have access to it. """ hint_template = "You are authenticated as {}" # Anonymous user should not be shown the hint response = self.client.get(self.index_url, follow=True) self.assertContains(response, "login-form") self.assertNotContains(response, hint_template.format(""), status_code=200) # Non-staff user should be shown the hint self.client.force_login(self.nostaffuser) response = self.client.get(self.index_url, follow=True) self.assertContains(response, "login-form") self.assertContains( response, hint_template.format(self.nostaffuser.username), status_code=200 ) def test_add_view(self): """Test add view restricts access and actually adds items.""" add_dict = { "title": "Døm ikke", "content": "great article
", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } # Change User should not have access to add articles self.client.force_login(self.changeuser) # make sure the view removes test cookie self.assertIs(self.client.session.test_cookie_worked(), False) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.status_code, 403) # Try POST just to make sure post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.post(reverse("admin:logout")) # View User should not have access to add articles self.client.force_login(self.viewuser) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.status_code, 403) # Try POST just to make sure post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) # Now give the user permission to add but not change. self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("add", Article._meta)) ) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.context["title"], "Add article") self.assertContains(response, "edited article
", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } article_change_url = reverse( "admin:admin_views_article_change", args=(self.a1.pk,) ) article_changelist_url = reverse("admin:admin_views_article_changelist") # add user should not be able to view the list of article or change any of them self.client.force_login(self.adduser) response = self.client.get(article_changelist_url) self.assertEqual(response.status_code, 403) response = self.client.get(article_change_url) self.assertEqual(response.status_code, 403) post = self.client.post(article_change_url, change_dict) self.assertEqual(post.status_code, 403) self.client.post(reverse("admin:logout")) # view user can view articles but not make changes. self.client.force_login(self.viewuser) response = self.client.get(article_changelist_url) self.assertContains( response, "Middle content
" ) self.client.post(reverse("admin:logout")) # change user can view all items and edit them self.client.force_login(self.changeuser) response = self.client.get(article_changelist_url) self.assertEqual(response.context["title"], "Select article to change") self.assertContains( response, "edited article
" ) # one error in form should produce singular error message, multiple # errors plural. change_dict["title"] = "" post = self.client.post(article_change_url, 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(article_change_url, 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.post(reverse("admin:logout")) # Test redirection when using row-level change permissions. Refs #11513. r1 = RowLevelChangePermissionModel.objects.create(id=1, name="odd id") r2 = RowLevelChangePermissionModel.objects.create(id=2, name="even id") r3 = RowLevelChangePermissionModel.objects.create(id=3, name="odd id mult 3") r6 = RowLevelChangePermissionModel.objects.create(id=6, name="even id mult 3") change_url_1 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r1.pk,) ) change_url_2 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r2.pk,) ) change_url_3 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r3.pk,) ) change_url_6 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r6.pk,) ) logins = [ self.superuser, self.viewuser, self.adduser, self.changeuser, self.deleteuser, ] for login_user in logins: with self.subTest(login_user.username): self.client.force_login(login_user) response = self.client.get(change_url_1) self.assertEqual(response.status_code, 403) response = self.client.post(change_url_1, {"name": "changed"}) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=1).name, "odd id" ) self.assertEqual(response.status_code, 403) response = self.client.get(change_url_2) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_2, {"name": "changed"}) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=2).name, "changed" ) self.assertRedirects(response, self.index_url) response = self.client.get(change_url_3) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_3, {"name": "changed"}) self.assertEqual(response.status_code, 403) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=3).name, "odd id mult 3", ) response = self.client.get(change_url_6) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_6, {"name": "changed"}) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=6).name, "changed" ) self.assertRedirects(response, self.index_url) self.client.post(reverse("admin:logout")) for login_user in [self.joepublicuser, self.nostaffuser]: with self.subTest(login_user.username): self.client.force_login(login_user) response = self.client.get(change_url_1, follow=True) self.assertContains(response, "login-form") response = self.client.post( change_url_1, {"name": "changed"}, follow=True ) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=1).name, "odd id" ) self.assertContains(response, "login-form") response = self.client.get(change_url_2, follow=True) self.assertContains(response, "login-form") response = self.client.post( change_url_2, {"name": "changed again"}, follow=True ) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=2).name, "changed" ) self.assertContains(response, "login-form") self.client.post(reverse("admin:logout")) def test_change_view_without_object_change_permission(self): """ The object should be read-only if the user has permission to view it and change objects of that type but not to change the current object. """ change_url = reverse("admin9:admin_views_article_change", args=(self.a1.pk,)) self.client.force_login(self.viewuser) response = self.client.get(change_url) self.assertEqual(response.context["title"], "View article") self.assertContains(response, "edited article
", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } article_change_url = reverse( "admin:admin_views_article_change", args=(self.a1.pk,) ) # Add user can perform "Save as new". article_count = Article.objects.count() self.client.force_login(self.adduser) post = self.client.post(article_change_url, change_dict_save_as_new) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), article_count + 1) self.client.logout() # Change user cannot perform "Save as new" (no 'add' permission). article_count = Article.objects.count() self.client.force_login(self.changeuser) post = self.client.post(article_change_url, change_dict_save_as_new) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), article_count) # User with both add and change permissions should be redirected to the # change page for the newly created object. article_count = Article.objects.count() self.client.force_login(self.superuser) post = self.client.post(article_change_url, change_dict_save_as_new) self.assertEqual(Article.objects.count(), article_count + 1) new_article = Article.objects.latest("id") self.assertRedirects( post, reverse("admin:admin_views_article_change", args=(new_article.pk,)) ) def test_change_view_with_view_only_inlines(self): """ User with change permission to a section but view-only for inlines. """ self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("change", Section._meta)) ) self.client.force_login(self.viewuser) # GET shows inlines. response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 3) # Valid POST changes the name. data = { "name": "Can edit name with view-only inlines", "article_set-TOTAL_FORMS": 3, "article_set-INITIAL_FORMS": 3, } response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Section.objects.get(pk=self.s1.pk).name, data["name"]) # Invalid POST reshows inlines. del data["name"] response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 3) def test_change_view_with_view_only_last_inline(self): self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("view", Section._meta)) ) self.client.force_login(self.viewuser) response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 3) # The last inline is not marked as empty. self.assertContains(response, 'id="article_set-2"') def test_change_view_with_view_and_add_inlines(self): """User has view and add permissions on the inline model.""" self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("change", Section._meta)) ) self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("add", Article._meta)) ) self.client.force_login(self.viewuser) # GET shows inlines. response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 6) # Valid POST creates a new article. data = { "name": "Can edit name with view-only inlines", "article_set-TOTAL_FORMS": 6, "article_set-INITIAL_FORMS": 3, "article_set-3-id": [""], "article_set-3-title": ["A title"], "article_set-3-content": ["Added content"], "article_set-3-date_0": ["2008-3-18"], "article_set-3-date_1": ["11:54:58"], "article_set-3-section": [str(self.s1.pk)], } response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Section.objects.get(pk=self.s1.pk).name, data["name"]) self.assertEqual(Article.objects.count(), 4) # Invalid POST reshows inlines. del data["name"] response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 6) def test_change_view_with_view_and_delete_inlines(self): """User has view and delete permissions on the inline model.""" self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("change", Section._meta)) ) self.client.force_login(self.viewuser) data = { "name": "Name is required.", "article_set-TOTAL_FORMS": 6, "article_set-INITIAL_FORMS": 3, "article_set-0-id": [str(self.a1.pk)], "article_set-0-DELETE": ["on"], } # Inline POST details are ignored without delete permission. response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Article.objects.count(), 3) # Deletion successful when delete permission is added. self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("delete", Article._meta)) ) data = { "name": "Name is required.", "article_set-TOTAL_FORMS": 6, "article_set-INITIAL_FORMS": 3, "article_set-0-id": [str(self.a1.pk)], "article_set-0-DELETE": ["on"], } response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Article.objects.count(), 2) def test_delete_view(self): """Delete view should restrict access and actually delete items.""" delete_dict = {"post": "yes"} delete_url = reverse("admin:admin_views_article_delete", args=(self.a1.pk,)) # add user should not be able to delete articles self.client.force_login(self.adduser) response = self.client.get(delete_url) self.assertEqual(response.status_code, 403) post = self.client.post(delete_url, delete_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.logout() # view user should not be able to delete articles self.client.force_login(self.viewuser) response = self.client.get(delete_url) self.assertEqual(response.status_code, 403) post = self.client.post(delete_url, delete_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.logout() # Delete user can delete self.client.force_login(self.deleteuser) response = self.client.get( reverse("admin:admin_views_section_delete", args=(self.s1.pk,)) ) self.assertContains(response, "Middle content
", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="Oldest content
", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) 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.v1 = Villain.objects.create(name="Adam") cls.v2 = Villain.objects.create(name="Sue") cls.sv1 = SuperVillain.objects.create(name="Bob") cls.pl1 = Plot.objects.create( name="World Domination", team_leader=cls.v1, contact=cls.v2 ) cls.pl2 = Plot.objects.create( name="World Peace", team_leader=cls.v2, contact=cls.v2 ) cls.pl3 = Plot.objects.create( name="Corn Conspiracy", team_leader=cls.v1, contact=cls.v1 ) cls.pd1 = PlotDetails.objects.create(details="almost finished", plot=cls.pl1) cls.sh1 = SecretHideout.objects.create( location="underground bunker", villain=cls.v1 ) cls.sh2 = SecretHideout.objects.create( location="floating castle", villain=cls.sv1 ) cls.ssh1 = SuperSecretHideout.objects.create( location="super floating castle!", supervillain=cls.sv1 ) cls.cy1 = CyclicOne.objects.create(name="I am recursive", two_id=1) cls.cy2 = CyclicTwo.objects.create(name="I am recursive too", one_id=1) def setUp(self): self.client.force_login(self.superuser) def test_nesting(self): """ Objects should be nested to display the relationships that cause them to be scheduled for deletion. """ pattern = re.compile( r'Middle content
", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="Oldest content
", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) 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.pk = ( "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 " r"""-_.!~*'() ;/?:@&=+$, <>#%" {}|\^[]`""" ) cls.m1 = ModelWithStringPrimaryKey.objects.create(string_pk=cls.pk) content_type_pk = ContentType.objects.get_for_model( ModelWithStringPrimaryKey ).pk user_pk = cls.superuser.pk LogEntry.objects.log_action( user_pk, content_type_pk, cls.pk, cls.pk, 2, change_message="Changed something", ) def setUp(self): self.client.force_login(self.superuser) 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( reverse( "admin:admin_views_modelwithstringprimarykey_history", args=(self.pk,) ) ) self.assertContains(response, escape(self.pk)) self.assertContains(response, "Changed something") def test_get_change_view(self): "Retrieving the object using urlencoded form of primary key should work" response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(self.pk,) ) ) self.assertContains(response, escape(self.pk)) def test_changelist_to_changeform_link(self): """ Link to the changeform of the object in changelist should use reverse() and be quoted. """ response = self.client.get( reverse("admin:admin_views_modelwithstringprimarykey_changelist") ) # this URL now comes through reverse(), thus url quoting and iri_to_uri encoding pk_final_url = escape(iri_to_uri(quote(self.pk))) change_url = reverse( "admin:admin_views_modelwithstringprimarykey_change", args=("__fk__",) ).replace("__fk__", pk_final_url) should_contain = 'Svært frustrerende med UnicodeDecodeErro
", book=cls.b1, ) cls.chap2 = Chapter.objects.create( title="Kjærlighet", content="La kjærligheten til de lidende seire.
", book=cls.b1, ) cls.chap3 = Chapter.objects.create( title="Kjærlighet", content="Noe innhold
", book=cls.b1 ) cls.chap4 = ChapterXtra1.objects.create( chap=cls.chap1, xtra="Middle content
", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="Oldest content
", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) 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.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) cls.per2 = Person.objects.create(name="Grace Hopper", gender=1, alive=False) cls.per3 = Person.objects.create(name="Guido van Rossum", gender=1, alive=True) def setUp(self): self.client.force_login(self.superuser) def test_inheritance(self): Podcast.objects.create( name="This Week in Django", release_date=datetime.date.today() ) response = self.client.get(reverse("admin:admin_views_podcast_changelist")) self.assertEqual(response.status_code, 200) def test_inheritance_2(self): Vodcast.objects.create(name="This Week in Django", released=True) response = self.client.get(reverse("admin:admin_views_vodcast_changelist")) self.assertEqual(response.status_code, 200) def test_custom_pk(self): Language.objects.create(iso="en", name="English", english_name="English") response = self.client.get(reverse("admin:admin_views_language_changelist")) self.assertEqual(response.status_code, 200) def test_changelist_input_html(self): response = self.client.get(reverse("admin:admin_views_person_changelist")) # 2 inputs per object(the field and the hidden id field) = 6 # 4 management hidden fields = 4 # 4 action inputs (3 regular checkboxes, 1 checkbox to select all) # main form submit button = 1 # search field and search submit button = 2 # CSRF field = 2 # field to track 'select all' across paginated views = 1 # 6 + 4 + 4 + 1 + 2 + 2 + 1 = 20 inputs self.assertContains(response, "Middle content
", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="Oldest content
", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) 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.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) cls.per2 = Person.objects.create(name="Grace Hopper", gender=1, alive=False) cls.per3 = Person.objects.create(name="Guido van Rossum", gender=1, alive=True) Person.objects.create(name="John Doe", gender=1) Person.objects.create(name='John O"Hara', gender=1) Person.objects.create(name="John O'Hara", gender=1) cls.t1 = Recommender.objects.create() cls.t2 = Recommendation.objects.create(the_recommender=cls.t1) cls.t3 = Recommender.objects.create() cls.t4 = Recommendation.objects.create(the_recommender=cls.t3) cls.tt1 = TitleTranslation.objects.create(title=cls.t1, text="Bar") cls.tt2 = TitleTranslation.objects.create(title=cls.t2, text="Foo") cls.tt3 = TitleTranslation.objects.create(title=cls.t3, text="Few") cls.tt4 = TitleTranslation.objects.create(title=cls.t4, text="Bas") def setUp(self): self.client.force_login(self.superuser) def test_search_on_sibling_models(self): "A search that mentions sibling models" response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=bar" ) # confirm the search returned 1 object self.assertContains(response, "\n1 recommendation\n") def test_with_fk_to_field(self): """ The to_field GET parameter is preserved when a search is performed. Refs #10918. """ response = self.client.get( reverse("admin:auth_user_changelist") + "?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( reverse("admin:admin_views_recommendation_changelist") + "?q=bar" ) # confirm the search returned one object self.assertContains(response, "\n1 recommendation\n") response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=ba" ) # confirm the search returned zero objects self.assertContains(response, "\n0 recommendations\n") def test_beginning_matches(self): response = self.client.get( reverse("admin:admin_views_person_changelist") + "?q=Gui" ) # confirm the search returned one object self.assertContains(response, "\n1 person\n") self.assertContains(response, "Guido") response = self.client.get( reverse("admin:admin_views_person_changelist") + "?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( reverse("admin:admin_views_pluggablesearchperson_changelist") + "?q=Bob" ) # confirm the search returned one object self.assertContains(response, "\n1 pluggable search person\n") self.assertContains(response, "Bob") response = self.client.get( reverse("admin:admin_views_pluggablesearchperson_changelist") + "?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_)"). """ # 1 query for session + 1 for fetching user # + 1 for filtered result + 1 for filtered count # + 1 for total count with self.assertNumQueries(5): response = self.client.get( reverse("admin:admin_views_person_changelist") + "?q=Gui" ) self.assertContains( response, """1 result (6 total)""", html=True, ) def test_no_total_count(self): """ #8408 -- "Show all" should be displayed instead of the total count if ModelAdmin.show_full_result_count is False. """ # 1 query for session + 1 for fetching user # + 1 for filtered result + 1 for filtered count with self.assertNumQueries(4): response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=bar" ) self.assertContains( response, """1 result (Show all)""", html=True, ) self.assertTrue(response.context["cl"].show_admin_actions) def test_search_with_spaces(self): url = reverse("admin:admin_views_person_changelist") + "?q=%s" tests = [ ('"John Doe"', 1), ("'John Doe'", 1), ("John Doe", 0), ('"John Doe" John', 1), ("'John Doe' John", 1), ("John Doe John", 0), ('"John Do"', 1), ("'John Do'", 1), ("'John O'Hara'", 0), ("'John O\\'Hara'", 1), ('"John O"Hara"', 0), ('"John O\\"Hara"', 1), ] for search, hits in tests: with self.subTest(search=search): response = self.client.get(url % search) self.assertContains(response, "\n%s person" % hits) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminInheritedInlinesTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) def setUp(self): self.client.force_login(self.superuser) def test_inline(self): """ Inline models which inherit from a common parent are correctly handled. """ foo_user = "foo username" bar_user = "bar username" name_re = re.compile(b'name="(.*?)"') # test the add case response = self.client.get(reverse("admin:admin_views_persona_add")) names = name_re.findall(response.content) names.remove(b"csrfmiddlewaretoken") # 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(reverse("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( reverse("admin:admin_views_persona_change", args=(persona_id,)) ) names = name_re.findall(response.content) names.remove(b"csrfmiddlewaretoken") # 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( reverse("admin:admin_views_persona_change", args=(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(ROOT_URLCONF="admin_views.urls") class TestCustomChangeList(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) def setUp(self): self.client.force_login(self.superuser) def test_custom_changelist(self): """ Validate that a custom ChangeList class can be used (#9749) """ # Insert some data post_data = {"name": "First Gadget"} response = self.client.post(reverse("admin:admin_views_gadget_add"), post_data) self.assertEqual(response.status_code, 302) # redirect somewhere # Hit the page once to get messages out of the queue message list response = self.client.get(reverse("admin:admin_views_gadget_changelist")) # Data is still not visible on the page response = self.client.get(reverse("admin:admin_views_gadget_changelist")) self.assertNotContains(response, "First Gadget") @override_settings(ROOT_URLCONF="admin_views.urls") class TestInlineNotEditable(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) def setUp(self): self.client.force_login(self.superuser) def test_GET_parent_add(self): """ InlineModelAdmin broken? """ response = self.client.get(reverse("admin:admin_views_parent_add")) self.assertEqual(response.status_code, 200) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminCustomQuerysetTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) cls.pks = [EmptyModel.objects.create().id for i in range(3)] def setUp(self): self.client.force_login(self.superuser) self.super_login = { REDIRECT_FIELD_NAME: reverse("admin:index"), "username": "super", "password": "secret", } def test_changelist_view(self): response = self.client.get(reverse("admin:admin_views_emptymodel_changelist")) for i in self.pks: if i > 1: self.assertContains(response, "Primary key = %s" % i) else: self.assertNotContains(response, "Primary key = %s" % i) def test_changelist_view_count_queries(self): # create 2 Person objects Person.objects.create(name="person1", gender=1) Person.objects.create(name="person2", gender=2) changelist_url = reverse("admin:admin_views_person_changelist") # 5 queries are expected: 1 for the session, 1 for the user, # 2 for the counts and 1 for the objects on the page with self.assertNumQueries(5): resp = self.client.get(changelist_url) self.assertEqual(resp.context["selection_note"], "0 of 2 selected") self.assertEqual(resp.context["selection_note_all"], "All 2 selected") with self.assertNumQueries(5): extra = {"q": "not_in_name"} resp = self.client.get(changelist_url, extra) self.assertEqual(resp.context["selection_note"], "0 of 0 selected") self.assertEqual(resp.context["selection_note_all"], "All 0 selected") with self.assertNumQueries(5): extra = {"q": "person"} resp = self.client.get(changelist_url, extra) self.assertEqual(resp.context["selection_note"], "0 of 2 selected") self.assertEqual(resp.context["selection_note_all"], "All 2 selected") with self.assertNumQueries(5): extra = {"gender__exact": "1"} resp = self.client.get(changelist_url, extra) self.assertEqual(resp.context["selection_note"], "0 of 1 selected") self.assertEqual(resp.context["selection_note_all"], "1 selected") def test_change_view(self): for i in self.pks: url = reverse("admin:admin_views_emptymodel_change", args=(i,)) response = self.client.get(url, follow=True) if i > 1: self.assertEqual(response.status_code, 200) else: self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["empty model with ID “1” doesn’t exist. Perhaps it was deleted?"], ) def test_add_model_modeladmin_defer_qs(self): # Test for #14529. defer() is used in ModelAdmin.get_queryset() # model has __str__ method self.assertEqual(CoverLetter.objects.count(), 0) # Emulate model instance creation via the admin post_data = { "author": "Candidate, Best", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_coverletter_add"), post_data, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(CoverLetter.objects.count(), 1) # Message should contain non-ugly model verbose name pk = CoverLetter.objects.all()[0].pk self.assertContains( response, 'Middle content
", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=s1, ) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_article_changelist") ) # Change popup self.selenium.find_element(By.ID, "change_id_form-0-section").click() self.wait_for_and_switch_to_popup() self.wait_for_text("#content h1", "Change section") name_input = self.selenium.find_element(By.ID, "id_name") name_input.clear() name_input.send_keys("edited section") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) # Hide sidebar. toggle_button = self.selenium.find_element( By.CSS_SELECTOR, "#toggle-nav-sidebar" ) toggle_button.click() select = Select(self.selenium.find_element(By.ID, "id_form-0-section")) self.assertEqual(select.first_selected_option.text, "edited section") # Rendered select2 input. select2_display = self.selenium.find_element( By.CLASS_NAME, "select2-selection__rendered" ) # Clear button (×\n) is included in text. self.assertEqual(select2_display.text, "×\nedited section") # Add popup self.selenium.find_element(By.ID, "add_id_form-0-section").click() self.wait_for_and_switch_to_popup() self.wait_for_text("#content h1", "Add section") self.selenium.find_element(By.ID, "id_name").send_keys("new section") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_form-0-section")) self.assertEqual(select.first_selected_option.text, "new section") select2_display = self.selenium.find_element( By.CLASS_NAME, "select2-selection__rendered" ) # Clear button (×\n) is included in text. self.assertEqual(select2_display.text, "×\nnew section") def test_inline_uuid_pk_edit_with_popup(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select parent = ParentWithUUIDPK.objects.create(title="test") related_with_parent = RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_change", args=(related_with_parent.id,), ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "change_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_parent")) self.assertEqual(select.first_selected_option.text, str(parent.id)) self.assertEqual( select.first_selected_option.get_attribute("value"), str(parent.id) ) def test_inline_uuid_pk_add_with_popup(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_relatedwithuuidpkmodel_add") ) self.selenium.find_element(By.ID, "add_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.ID, "id_title").send_keys("test") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_parent")) uuid_id = str(ParentWithUUIDPK.objects.first().id) self.assertEqual(select.first_selected_option.text, uuid_id) self.assertEqual(select.first_selected_option.get_attribute("value"), uuid_id) def test_inline_uuid_pk_delete_with_popup(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select parent = ParentWithUUIDPK.objects.create(title="test") related_with_parent = RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_change", args=(related_with_parent.id,), ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "delete_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.XPATH, '//input[@value="Yes, I’m sure"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_parent")) self.assertEqual(ParentWithUUIDPK.objects.count(), 0) self.assertEqual(select.first_selected_option.text, "---------") self.assertEqual(select.first_selected_option.get_attribute("value"), "") def test_inline_with_popup_cancel_delete(self): """Clicking ""No, take me back" on a delete popup closes the window.""" from selenium.webdriver.common.by import By parent = ParentWithUUIDPK.objects.create(title="test") related_with_parent = RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_change", args=(related_with_parent.id,), ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "delete_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.XPATH, '//a[text()="No, take me back"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertEqual(len(self.selenium.window_handles), 1) def test_list_editable_raw_id_fields(self): from selenium.webdriver.common.by import By parent = ParentWithUUIDPK.objects.create(title="test") parent2 = ParentWithUUIDPK.objects.create(title="test2") RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_changelist", current_app=site2.name, ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "lookup_id_form-0-parent").click() self.wait_for_and_switch_to_popup() # Select "parent2" in the popup. self.selenium.find_element(By.LINK_TEXT, str(parent2.pk)).click() self.selenium.switch_to.window(self.selenium.window_handles[0]) # The newly selected pk should appear in the raw id input. value = self.selenium.find_element(By.ID, "id_form-0-parent").get_attribute( "value" ) self.assertEqual(value, str(parent2.pk)) def test_input_element_font(self): """ Browsers' default stylesheets override the font of inputs. The admin adds additional CSS to handle this. """ from selenium.webdriver.common.by import By self.selenium.get(self.live_server_url + reverse("admin:login")) element = self.selenium.find_element(By.ID, "id_username") # Some browsers quotes the fonts, some don't. fonts = [ font.strip().strip('"') for font in element.value_of_css_property("font-family").split(",") ] self.assertEqual( fonts, [ "-apple-system", "BlinkMacSystemFont", "Segoe UI", "system-ui", "Roboto", "Helvetica Neue", "Arial", "sans-serif", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", ], ) def test_search_input_filtered_page(self): from selenium.webdriver.common.by import By Person.objects.create(name="Guido van Rossum", gender=1, alive=True) Person.objects.create(name="Grace Hopper", gender=1, alive=False) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) person_url = reverse("admin:admin_views_person_changelist") + "?q=Gui" self.selenium.get(self.live_server_url + person_url) self.assertGreater( self.selenium.find_element(By.ID, "searchbar").rect["width"], 50, ) def test_related_popup_index(self): """ Create a chain of 'self' related objects via popups. """ from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin:admin_views_box_add", current_app=site.name) self.selenium.get(self.live_server_url + add_url) base_window = self.selenium.current_window_handle self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup() popup_window_test = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=3) popup_window_test2 = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test2") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=4) self.selenium.find_element(By.ID, "id_title").send_keys("test3") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(popup_window_test2) select = Select(self.selenium.find_element(By.ID, "id_next_box")) next_box_id = str(Box.objects.get(title="test3").id) self.assertEqual( select.first_selected_option.get_attribute("value"), next_box_id ) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(popup_window_test) select = Select(self.selenium.find_element(By.ID, "id_next_box")) next_box_id = str(Box.objects.get(title="test2").id) self.assertEqual( select.first_selected_option.get_attribute("value"), next_box_id ) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(base_window) select = Select(self.selenium.find_element(By.ID, "id_next_box")) next_box_id = str(Box.objects.get(title="test").id) self.assertEqual( select.first_selected_option.get_attribute("value"), next_box_id ) def test_related_popup_incorrect_close(self): """ Cleanup child popups when closing a parent popup. """ from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin:admin_views_box_add", current_app=site.name) self.selenium.get(self.live_server_url + add_url) self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup() test_window = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=3) test2_window = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test2") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=4) self.assertEqual(len(self.selenium.window_handles), 4) self.selenium.switch_to.window(test2_window) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.wait_until(lambda d: len(d.window_handles) == 2, 1) self.assertEqual(len(self.selenium.window_handles), 2) # Close final popup to clean up test. self.selenium.switch_to.window(test_window) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.wait_until(lambda d: len(d.window_handles) == 1, 1) self.selenium.switch_to.window(self.selenium.window_handles[-1]) def test_hidden_fields_small_window(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index"), ) self.selenium.get(self.live_server_url + reverse("admin:admin_views_story_add")) field_title = self.selenium.find_element(By.CLASS_NAME, "field-title") current_size = self.selenium.get_window_size() try: self.selenium.set_window_size(1024, 768) self.assertIs(field_title.is_displayed(), False) self.selenium.set_window_size(767, 575) self.assertIs(field_title.is_displayed(), False) finally: self.selenium.set_window_size(current_size["width"], current_size["height"]) def test_updating_related_objects_updates_fk_selects_except_autocompletes(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select born_country_select_id = "id_born_country" living_country_select_id = "id_living_country" living_country_select2_textbox_id = "select2-id_living_country-container" favorite_country_to_vacation_select_id = "id_favorite_country_to_vacation" continent_select_id = "id_continent" def _get_HTML_inside_element_by_id(id_): return self.selenium.find_element(By.ID, id_).get_attribute("innerHTML") def _get_text_inside_element_by_selector(selector): return self.selenium.find_element(By.CSS_SELECTOR, selector).get_attribute( "innerText" ) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin:admin_views_traveler_add") self.selenium.get(self.live_server_url + add_url) # Add new Country from the born_country select. self.selenium.find_element(By.ID, f"add_{born_country_select_id}").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.ID, "id_name").send_keys("Argentina") continent_select = Select( self.selenium.find_element(By.ID, continent_select_id) ) continent_select.select_by_visible_text("South America") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertHTMLEqual( _get_HTML_inside_element_by_id(born_country_select_id), """ """, ) # Argentina isn't added to the living_country select nor selected by # the select2 widget. self.assertEqual( _get_text_inside_element_by_selector(f"#{living_country_select_id}"), "" ) self.assertEqual( _get_text_inside_element_by_selector( f"#{living_country_select2_textbox_id}" ), "", ) # Argentina won't appear because favorite_country_to_vacation field has # limit_choices_to. self.assertHTMLEqual( _get_HTML_inside_element_by_id(favorite_country_to_vacation_select_id), '', ) # Add new Country from the living_country select. self.selenium.find_element(By.ID, f"add_{living_country_select_id}").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.ID, "id_name").send_keys("Spain") continent_select = Select( self.selenium.find_element(By.ID, continent_select_id) ) continent_select.select_by_visible_text("Europe") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertHTMLEqual( _get_HTML_inside_element_by_id(born_country_select_id), """ """, ) # Spain is added to the living_country select and it's also selected by # the select2 widget. self.assertEqual( _get_text_inside_element_by_selector(f"#{living_country_select_id} option"), "Spain", ) self.assertEqual( _get_text_inside_element_by_selector( f"#{living_country_select2_textbox_id}" ), "Spain", ) # Spain won't appear because favorite_country_to_vacation field has # limit_choices_to. self.assertHTMLEqual( _get_HTML_inside_element_by_id(favorite_country_to_vacation_select_id), '', ) # Edit second Country created from living_country select. favorite_select = Select( self.selenium.find_element(By.ID, living_country_select_id) ) favorite_select.select_by_visible_text("Spain") self.selenium.find_element(By.ID, f"change_{living_country_select_id}").click() self.wait_for_and_switch_to_popup() favorite_name_input = self.selenium.find_element(By.ID, "id_name") favorite_name_input.clear() favorite_name_input.send_keys("Italy") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertHTMLEqual( _get_HTML_inside_element_by_id(born_country_select_id), """ """, ) # Italy is added to the living_country select and it's also selected by # the select2 widget. self.assertEqual( _get_text_inside_element_by_selector(f"#{living_country_select_id} option"), "Italy", ) self.assertEqual( _get_text_inside_element_by_selector( f"#{living_country_select2_textbox_id}" ), "Italy", ) # favorite_country_to_vacation field has no options. self.assertHTMLEqual( _get_HTML_inside_element_by_id(favorite_country_to_vacation_select_id), '', ) # Add a new Asian country. self.selenium.find_element( By.ID, f"add_{favorite_country_to_vacation_select_id}" ).click() self.wait_for_and_switch_to_popup() favorite_name_input = self.selenium.find_element(By.ID, "id_name") favorite_name_input.send_keys("Qatar") continent_select = Select( self.selenium.find_element(By.ID, continent_select_id) ) continent_select.select_by_visible_text("Asia") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) # Submit the new Traveler. self.selenium.find_element(By.CSS_SELECTOR, '[name="_save"]').click() traveler = Traveler.objects.get() self.assertEqual(traveler.born_country.name, "Argentina") self.assertEqual(traveler.living_country.name, "Italy") self.assertEqual(traveler.favorite_country_to_vacation.name, "Qatar") def test_redirect_on_add_view_add_another_button(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin7:admin_views_section_add") self.selenium.get(self.live_server_url + add_url) name_input = self.selenium.find_element(By.ID, "id_name") name_input.send_keys("Test section 1") self.selenium.find_element( By.XPATH, '//input[@value="Save and add another"]' ).click() self.assertEqual(Section.objects.count(), 1) name_input = self.selenium.find_element(By.ID, "id_name") name_input.send_keys("Test section 2") self.selenium.find_element( By.XPATH, '//input[@value="Save and add another"]' ).click() self.assertEqual(Section.objects.count(), 2) def test_redirect_on_add_view_continue_button(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin7:admin_views_section_add") self.selenium.get(self.live_server_url + add_url) name_input = self.selenium.find_element(By.ID, "id_name") name_input.send_keys("Test section 1") self.selenium.find_element( By.XPATH, '//input[@value="Save and continue editing"]' ).click() self.assertEqual(Section.objects.count(), 1) name_input = self.selenium.find_element(By.ID, "id_name") name_input_value = name_input.get_attribute("value") self.assertEqual(name_input_value, "Test section 1") @override_settings(ROOT_URLCONF="admin_views.urls") class ReadonlyTest(AdminFieldExtractionMixin, TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) def setUp(self): self.client.force_login(self.superuser) def test_readonly_get(self): response = self.client.get(reverse("admin:admin_views_post_add")) self.assertNotContains(response, 'name="posted"') # 3 fields + 2 submit buttons + 5 inline management form fields, + 2 # hidden fields for inlines + 1 field for the inline + 2 empty form # + 1 logout form. self.assertContains(response, "Awesomeness level:") self.assertContains(response, "Very awesome.") self.assertContains(response, "Unknown coolness.") self.assertContains(response, "foo") # Multiline text in a readonly field getsMiddle content
", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="Oldest content
", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) 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.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) cls.per2 = Person.objects.create(name="Grace Hopper", gender=1, alive=False) cls.per3 = Person.objects.create(name="Guido van Rossum", gender=1, alive=True) def setUp(self): self.client.force_login(self.superuser) def test_save_button(self): user_count = User.objects.count() response = self.client.post( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "newpassword", }, ) new_user = User.objects.get(username="newuser") self.assertRedirects( response, reverse("admin:auth_user_change", args=(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( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "newpassword", "_continue": "1", }, ) new_user = User.objects.get(username="newuser") new_user_url = reverse("admin:auth_user_change", args=(new_user.pk,)) self.assertRedirects(response, new_user_url, fetch_redirect_response=False) self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) response = self.client.get(new_user_url) self.assertContains( response, 'Middle content
", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="Oldest content
", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) 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" ) def setUp(self): self.client.force_login(self.superuser) def test_field_prefix_css_classes(self): """ Fields have a CSS class name with a 'field-' prefix. """ response = self.client.get(reverse("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, '