# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime import os import re import unittest from django.contrib.admin import ModelAdmin from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.models import DELETION, LogEntry from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.templatetags.admin_static import static from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase from django.contrib.admin.utils import quote from django.contrib.admin.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.contrib.staticfiles.storage import staticfiles_storage from django.core import mail from django.core.checks import Error from django.core.files import temp as tempfile from django.core.urlresolvers import ( NoReverseMatch, get_script_prefix, resolve, reverse, set_script_prefix, ) 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 patch_logger from django.utils import formats, six, translation from django.utils._os import upath from django.utils.cache import get_max_age from django.utils.encoding import force_bytes, force_text, iri_to_uri from django.utils.html import escape from django.utils.http import urlencode from django.utils.six.moves.urllib.parse import parse_qsl, urljoin, urlparse from . import customadmin from .admin import CityAdmin, site, site2 from .models import ( Actor, AdminOrderedAdminMethod, AdminOrderedCallable, AdminOrderedField, AdminOrderedModelMethod, Answer, Article, BarAccount, Book, Category, Chapter, Character, Child, Choice, City, Collector, Color2, ComplexSortedPerson, CoverLetter, CustomArticle, DooHickey, Employee, EmptyModel, FancyDoodad, FieldOverridePost, FilteredManager, FooAccount, FoodDelivery, FunkyTag, Gallery, Grommet, Inquisition, Language, MainPrepopulated, ModelWithStringPrimaryKey, OtherStory, Paper, Parent, ParentWithDependentChildren, Person, Persona, Picture, Pizza, Plot, PluggableSearchPerson, Podcast, Post, Promo, Question, RelatedPrepopulated, Report, Restaurant, RowLevelChangePermissionModel, Section, ShortMessage, Simple, Story, Subscriber, Telegram, Topping, UnchangeableObject, UndeletableObject, UnorderedObject, 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." @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF="admin_views.urls", USE_I18N=True, USE_L10N=False, LANGUAGE_CODE='en') class AdminViewBasicTestCase(TestCase): fixtures = ['admin-views-users.xml', 'admin-views-colors.xml', 'admin-views-fabrics.xml', 'admin-views-books.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): formats.reset_format_cache() def assertContentBefore(self, response, text1, text2, failing_msg=None): """ Testing utility asserting that text1 appears before text2 in response content. """ self.assertEqual(response.status_code, 200) self.assertLess(response.content.index(force_bytes(text1)), response.content.index(force_bytes(text2)), failing_msg) class AdminViewBasicTest(AdminViewBasicTestCase): def test_trailing_slash_required(self): """ If you leave off the trailing slash, app should redirect and add it. """ 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_admin_static_template_tag(self): """ Test that admin_static.static is pointing to the collectstatic version (as django.contrib.collectstatic is in installed apps). """ old_url = staticfiles_storage.base_url staticfiles_storage.base_url = '/test/' try: self.assertEqual(static('path'), '/test/path') finally: staticfiles_storage.base_url = old_url def test_basic_add_GET(self): """ A smoke test to ensure GET on the add_view works. """ response = self.client.get(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.assertEqual(response.status_code, 200) self.assertContains(response, 'value="My Section"', msg_prefix="Couldn't find an input with the right value in the response") def test_basic_edit_GET(self): """ A smoke test to ensure GET on the change_view works. """ response = self.client.get(reverse('admin:admin_views_section_change', args=(1,))) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_basic_edit_GET_string_PK(self): """ Ensure GET on the change_view works (returns an HTTP 404 error, see #11191) when passing a string as the PK argument for a model with an integer PK field. """ response = self.client.get(reverse('admin:admin_views_section_change', args=('abc',))) self.assertEqual(response.status_code, 404) 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=(1,)).replace('change/', '') ) self.assertRedirects(response, reverse('admin:admin_views_section_change', args=(1,))) def test_basic_inheritance_GET_string_PK(self): """ Ensure GET on the change_view works on inherited models (returns an HTTP 404 error, see #19951) when passing a string as the PK argument for a model with an integer PK field. """ response = self.client.get(reverse('admin:admin_views_supervillain_change', args=('abc',))) self.assertEqual(response.status_code, 404) def test_basic_add_POST(self): """ A smoke test to ensure POST on add_view works. """ post_data = { "name": "Another Section", # inline data "article_set-TOTAL_FORMS": "3", "article_set-INITIAL_FORMS": "0", "article_set-MAX_NUM_FORMS": "0", } response = self.client.post(reverse('admin:admin_views_section_add'), post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def test_popup_add_POST(self): """ Ensure http response from a popup is properly escaped. """ post_data = { '_popup': '1', 'title': 'title with a new\nline', 'content': 'some content', 'date_0': '2010-09-10', 'date_1': '14:55:39', } response = self.client.post(reverse('admin:admin_views_article_add'), post_data) self.assertEqual(response.status_code, 200) self.assertContains(response, 'dismissAddRelatedObjectPopup') self.assertContains(response, 'title with a new\\u000Aline') # Post data for edit inline inline_post_data = { "name": "Test section", # inline data "article_set-TOTAL_FORMS": "6", "article_set-INITIAL_FORMS": "3", "article_set-MAX_NUM_FORMS": "0", "article_set-0-id": "1", # there is no title in database, give one here or formset will fail. "article_set-0-title": "Norske bostaver æøå skaper problemer", "article_set-0-content": "<p>Middle content</p>", "article_set-0-date_0": "2008-03-18", "article_set-0-date_1": "11:54:58", "article_set-0-section": "1", "article_set-1-id": "2", "article_set-1-title": "Need a title.", "article_set-1-content": "<p>Oldest content</p>", "article_set-1-date_0": "2000-03-18", "article_set-1-date_1": "11:54:58", "article_set-2-id": "3", "article_set-2-title": "Need a title.", "article_set-2-content": "<p>Newest content</p>", "article_set-2-date_0": "2009-03-18", "article_set-2-date_1": "11:54:58", "article_set-3-id": "", "article_set-3-title": "", "article_set-3-content": "", "article_set-3-date_0": "", "article_set-3-date_1": "", "article_set-4-id": "", "article_set-4-title": "", "article_set-4-content": "", "article_set-4-date_0": "", "article_set-4-date_1": "", "article_set-5-id": "", "article_set-5-title": "", "article_set-5-content": "", "article_set-5-date_0": "", "article_set-5-date_1": "", } def test_basic_edit_POST(self): """ A smoke test to ensure POST on edit_view works. """ response = self.client.post(reverse('admin:admin_views_section_change', args=(1,)), 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=(1,)), 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=(1,)), 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_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_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) """ response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '6'}) self.assertContentBefore(response, '2009', '2008', "Results of sorting on ModelAdmin method are out of order.") self.assertContentBefore(response, '2008', '2000', "Results of sorting on ModelAdmin method are out of order.") # Let's make sure the ordering is right and that we don't get a # FieldError when we change to descending order response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '-6'}) self.assertContentBefore(response, '2000', '2008', "Results of sorting on ModelAdmin method are out of order.") self.assertContentBefore(response, '2008', '2009', "Results of sorting on ModelAdmin method are out of order.") def test_change_list_sorting_multiple(self): p1 = Person.objects.create(name="Chris", gender=1, alive=True) p2 = Person.objects.create(name="Chris", gender=2, alive=True) p3 = Person.objects.create(name="Bob", gender=1, alive=True) link1 = reverse('admin:admin_views_person_change', args=(p1.pk,)) link2 = reverse('admin:admin_views_person_change', args=(p2.pk,)) link3 = reverse('admin:admin_views_person_change', args=(p3.pk,)) # Sort by name, gender response = self.client.get(reverse('admin:admin_views_person_changelist'), {'o': '1.2'}) self.assertContentBefore(response, link3, link1) self.assertContentBefore(response, link1, link2) # Sort by gender descending, name response = self.client.get(reverse('admin:admin_views_person_changelist'), {'o': '-2.1'}) self.assertContentBefore(response, link2, link3) self.assertContentBefore(response, link3, link1) def test_change_list_sorting_preserve_queryset_ordering(self): """ If no ordering is defined in `ModelAdmin.ordering` or in the query string, then the underlying order of the queryset should not be changed, even if it is defined in `Modeladmin.get_queryset()`. Refs #11868, #7309. """ p1 = Person.objects.create(name="Amy", gender=1, alive=True, age=80) p2 = Person.objects.create(name="Bob", gender=1, alive=True, age=70) p3 = Person.objects.create(name="Chris", gender=2, alive=False, age=60) link1 = reverse('admin:admin_views_person_change', args=(p1.pk,)) link2 = reverse('admin:admin_views_person_change', args=(p2.pk,)) link3 = reverse('admin:admin_views_person_change', args=(p3.pk,)) response = self.client.get(reverse('admin:admin_views_person_changelist'), {}) self.assertContentBefore(response, link3, link2) self.assertContentBefore(response, link2, link1) def test_change_list_sorting_model_meta(self): # Test ordering on Model Meta is respected l1 = Language.objects.create(iso='ur', name='Urdu') l2 = Language.objects.create(iso='ar', name='Arabic') link1 = reverse('admin:admin_views_language_change', args=(quote(l1.pk),)) link2 = reverse('admin:admin_views_language_change', args=(quote(l2.pk),)) response = self.client.get(reverse('admin:admin_views_language_changelist'), {}) self.assertContentBefore(response, link2, link1) # Test we can override with query string response = self.client.get(reverse('admin:admin_views_language_changelist'), {'o': '-1'}) self.assertContentBefore(response, link1, link2) def test_change_list_sorting_override_model_admin(self): # Test ordering on Model Admin is respected, and overrides Model Meta dt = datetime.datetime.now() p1 = Podcast.objects.create(name="A", release_date=dt) p2 = Podcast.objects.create(name="B", release_date=dt - datetime.timedelta(10)) link1 = reverse('admin:admin_views_podcast_change', args=(p1.pk,)) link2 = reverse('admin:admin_views_podcast_change', args=(p2.pk,)) response = self.client.get(reverse('admin:admin_views_podcast_changelist'), {}) self.assertContentBefore(response, link1, link2) def test_multiple_sort_same_field(self): # Check that we get the columns we expect if we have two columns # that correspond to the same ordering field dt = datetime.datetime.now() p1 = Podcast.objects.create(name="A", release_date=dt) p2 = Podcast.objects.create(name="B", release_date=dt - datetime.timedelta(10)) link1 = reverse('admin:admin_views_podcast_change', args=(quote(p1.pk),)) link2 = reverse('admin:admin_views_podcast_change', args=(quote(p2.pk),)) response = self.client.get(reverse('admin:admin_views_podcast_changelist'), {}) self.assertContentBefore(response, link1, link2) p1 = ComplexSortedPerson.objects.create(name="Bob", age=10) p2 = ComplexSortedPerson.objects.create(name="Amy", age=20) link1 = reverse('admin:admin_views_complexsortedperson_change', args=(p1.pk,)) link2 = reverse('admin:admin_views_complexsortedperson_change', args=(p2.pk,)) response = self.client.get(reverse('admin:admin_views_complexsortedperson_changelist'), {}) # Should have 5 columns (including action checkbox col) self.assertContains(response, '
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.all().count(), 1) article_pk = CustomArticle.objects.all()[0].pk # Test custom delete, change, and object history templates # Test custom change form template response = self.client.get(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') def test_extended_bodyclass_template_change_form(self): """ Ensure that the admin/change_form.html template uses block.super in the bodyclass block. """ response = self.client.get(reverse('admin:admin_views_section_add')) self.assertContains(response, 'bodyclass_consistency_check ') def test_extended_bodyclass_template_change_password(self): """ Ensure that the auth/user/change_password.html template uses block super in the bodyclass block. """ user = User.objects.get(username='super') response = self.client.get(reverse('admin:auth_user_password_change', args=(user.id,))) self.assertContains(response, 'bodyclass_consistency_check ') def test_extended_bodyclass_template_index(self): """ Ensure that the admin/index.html template uses block.super in the bodyclass block. """ response = self.client.get(reverse('admin:index')) self.assertContains(response, 'bodyclass_consistency_check ') def test_extended_bodyclass_change_list(self): """ Ensure that the admin/change_list.html' template uses block.super in the bodyclass block. """ response = self.client.get(reverse('admin:admin_views_article_changelist')) self.assertContains(response, 'bodyclass_consistency_check ') def test_extended_bodyclass_template_login(self): """ Ensure that the admin/login.html template uses block.super in the bodyclass block. """ self.client.logout() response = self.client.get(reverse('admin:login')) self.assertContains(response, 'bodyclass_consistency_check ') def test_extended_bodyclass_template_delete_confirmation(self): """ Ensure that the admin/delete_confirmation.html template uses block.super in the bodyclass block. """ group = Group.objects.create(name="foogroup") response = self.client.get(reverse('admin:auth_group_delete', args=(group.id,))) self.assertContains(response, 'bodyclass_consistency_check ') def test_extended_bodyclass_template_delete_selected_confirmation(self): """ Ensure that the admin/delete_selected_confirmation.html template uses block.super in bodyclass block. """ group = Group.objects.create(name="foogroup") post_data = { 'action': 'delete_selected', 'selected_across': '0', 'index': '0', '_selected_action': group.id } response = self.client.post(reverse('admin:auth_group_changelist'), post_data) self.assertEqual(response.context['site_header'], 'Django administration') self.assertContains(response, 'bodyclass_consistency_check ') def test_filter_with_custom_template(self): """ Ensure that one can use a custom template to render an admin filter. Refs #17515. """ response = self.client.get(reverse('admin:admin_views_color2_changelist')) self.assertTemplateUsed(response, 'custom_filter_template.html') @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF="admin_views.urls") class AdminViewFormUrlTest(TestCase): fixtures = ["admin-views-users.xml"] current_app = "admin3" def setUp(self): self.client.login(username='super', password='secret') def test_change_form_URL_has_correct_value(self): """ Tests whether change_view has form_url in response.context """ response = self.client.get( reverse('admin:admin_views_section_change', args=(1,), 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): """ Tests that the behavior for setting initial form data can be overridden in the ModelAdmin class. Usually, the initial value is set via the GET params. """ response = self.client.get( 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(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF="admin_views.urls") class AdminJavaScriptTest(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def test_js_minified_only_if_debug_is_false(self): """ Ensure that the minified versions of the JS files are only used when DEBUG is False. Refs #17521. """ with override_settings(DEBUG=False): response = self.client.get(reverse('admin:admin_views_section_add')) self.assertNotContains(response, 'jquery.js') self.assertContains(response, 'jquery.min.js') self.assertNotContains(response, 'prepopulate.js') self.assertContains(response, 'prepopulate.min.js') self.assertNotContains(response, 'actions.js') self.assertContains(response, 'actions.min.js') self.assertNotContains(response, 'collapse.js') self.assertContains(response, 'collapse.min.js') self.assertNotContains(response, 'inlines.js') self.assertContains(response, 'inlines.min.js') with override_settings(DEBUG=True): response = self.client.get(reverse('admin:admin_views_section_add')) self.assertContains(response, 'jquery.js') self.assertNotContains(response, 'jquery.min.js') self.assertContains(response, 'prepopulate.js') self.assertNotContains(response, 'prepopulate.min.js') self.assertContains(response, 'actions.js') self.assertNotContains(response, 'actions.min.js') self.assertContains(response, 'collapse.js') self.assertNotContains(response, 'collapse.min.js') self.assertContains(response, 'inlines.js') self.assertNotContains(response, 'inlines.min.js') @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF="admin_views.urls") class SaveAsTests(TestCase): fixtures = ['admin-views-users.xml', 'admin-views-person.xml'] def setUp(self): self.client.login(username='super', password='secret') def test_save_as_duplication(self): """Ensure save as actually creates a new person""" post_data = {'_saveasnew': '', 'name': 'John M', 'gender': 1, 'age': 42} self.client.post(reverse('admin:admin_views_person_change', args=(1,)), post_data) self.assertEqual(len(Person.objects.filter(name='John M')), 1) self.assertEqual(len(Person.objects.filter(id=1)), 1) def test_save_as_display(self): """ Ensure that 'save as' is displayed when activated and after submitting invalid data aside save_as_new will not show us a form to overwrite the initial model. """ change_url = reverse('admin:admin_views_person_change', args=(1,)) response = self.client.get(change_url) self.assertTrue(response.context['save_as']) post_data = {'_saveasnew': '', 'name': 'John M', 'gender': 3, 'alive': 'checked'} response = self.client.post(change_url, post_data) self.assertEqual(response.context['form_url'], reverse('admin:admin_views_person_add')) @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.assertEqual(login.status_code, 200) self.assertContains(login, 'custom form error') def test_custom_admin_site_login_template(self): self.client.logout() response = self.client.get(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.get(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): try: response = self.client.get(reverse('admin2:index')) except TypeError: self.fail('AdminSite.index_template should accept a list of template paths') self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, 'custom_admin/index.html') self.assertContains(response, 'Hello from a custom index template *bar*') def test_custom_admin_site_app_index_view_and_template(self): response = self.client.get(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.login(username='super', password='secret') 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.login(username='super', password='secret') su = User.objects.get(username='super') try: response = self.client.get( reverse('admin4:auth_user_password_change', args=(su.pk,)) ) except TypeError: self.fail('ModelAdmin.change_user_password_template should accept a list of template paths') self.assertEqual(response.status_code, 200) def get_perm(Model, perm): """Return the permission object, for the Model""" ct = ContentType.objects.get_for_model(Model) return Permission.objects.get(content_type=ct, codename=perm) @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF="admin_views.urls") class AdminViewPermissionsTest(TestCase): """Tests for Admin Views Permissions.""" fixtures = ['admin-views-users.xml'] @classmethod def setUpTestData(cls): super(AdminViewPermissionsTest, cls).setUpTestData() # Setup permissions, for our users who can add, change, and delete. # We can't put this into the fixture, because the content type id # and the permission id could be different on each run of the test. opts = Article._meta # User who can add Articles add_user = User.objects.get(username='adduser') add_user.user_permissions.add(get_perm(Article, get_permission_codename('add', opts))) # User who can change Articles change_user = User.objects.get(username='changeuser') change_user.user_permissions.add(get_perm(Article, get_permission_codename('change', opts))) change_user2 = User.objects.get(username='nostaff') change_user2.user_permissions.add(get_perm(Article, get_permission_codename('change', opts))) # User who can delete Articles delete_user = User.objects.get(username='deleteuser') delete_user.user_permissions.add(get_perm(Article, get_permission_codename('delete', opts))) delete_user.user_permissions.add(get_perm(Section, get_permission_codename('delete', Section._meta))) # login POST dicts 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.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.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.get(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) # 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.get(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.get(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.get(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.assertEqual(login.status_code, 200) 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) form = login.context[0].get('form') self.assertEqual(form.errors['username'][0], 'This field is required.') 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.assertEqual(login.status_code, 200) 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.get(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.get(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.assertEqual(login.status_code, 200) self.assertContains(login, ERROR_MESSAGE) # Establish a valid admin session login = self.client.post(login_url, self.super_login) self.assertRedirects(login, 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.get(reverse('admin:logout')) def test_add_view(self): """Test add view restricts access and actually adds items.""" login_url = '%s?next=%s' % (reverse('admin:login'), reverse('admin:index')) add_dict = {'title': 'Døm ikke', 'content': 'great article
', 'date_0': '2008-03-18', 'date_1': '10:54:39', 'section': 1} # Change User should not have access to add articles self.client.get(self.index_url) self.client.post(login_url, self.changeuser_login) # make sure the view removes test cookie self.assertEqual(self.client.session.test_cookie_worked(), False) response = self.client.get(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.get(reverse('admin:logout')) # Add user may login and POST to add view, then redirect to admin root self.client.get(self.index_url) self.client.post(login_url, self.adduser_login) addpage = self.client.get(reverse('admin:admin_views_article_add')) change_list_link = '› Articles' % reverse('admin:admin_views_article_changelist') self.assertNotContains(addpage, change_list_link, msg_prefix='User restricted to add permission is given link to change list view in breadcrumbs.') post = self.client.post(reverse('admin:admin_views_article_add'), add_dict) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), 4) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Greetings from a created object') self.client.get(reverse('admin:logout')) # Super can add too, but is redirected to the change list view self.client.get(self.index_url) self.client.post(login_url, self.super_login) addpage = self.client.get(reverse('admin:admin_views_article_add')) self.assertContains(addpage, change_list_link, msg_prefix='Unrestricted user is not given link to change list view in breadcrumbs.') post = self.client.post(reverse('admin:admin_views_article_add'), add_dict) self.assertRedirects(post, reverse('admin:admin_views_article_changelist')) self.assertEqual(Article.objects.count(), 5) self.client.get(reverse('admin:logout')) # 8509 - if a normal user is already logged in, it is possible # to change user into the superuser without error self.client.login(username='joepublic', password='secret') # Check and make sure that if user expires, data still persists self.client.get(self.index_url) self.client.post(login_url, self.super_login) # make sure the view removes test cookie self.assertEqual(self.client.session.test_cookie_worked(), False) def test_change_view(self): """Change view should restrict access and allow users to edit items.""" login_url = '%s?next=%s' % (reverse('admin:login'), reverse('admin:index')) change_dict = {'title': 'Ikke fordømt', 'content': 'edited article
', 'date_0': '2008-03-18', 'date_1': '10:54:39', 'section': 1} article_change_url = reverse('admin:admin_views_article_change', args=(1,)) 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.get(self.index_url) self.client.post(login_url, self.adduser_login) 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.get(reverse('admin:logout')) # change user can view all items and edit them self.client.get(self.index_url) self.client.post(login_url, self.changeuser_login) response = self.client.get(article_changelist_url) self.assertEqual(response.status_code, 200) response = self.client.get(article_change_url) self.assertEqual(response.status_code, 200) post = self.client.post(article_change_url, change_dict) self.assertRedirects(post, article_changelist_url) self.assertEqual(Article.objects.get(pk=1).content, 'edited article
') # one error in form should produce singular error message, multiple errors plural change_dict['title'] = '' post = self.client.post(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.get(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") change_url_1 = reverse('admin:admin_views_rowlevelchangepermissionmodel_change', args=(r1.pk,)) change_url_2 = reverse('admin:admin_views_rowlevelchangepermissionmodel_change', args=(r2.pk,)) for login_dict in [self.super_login, self.changeuser_login, self.adduser_login, self.deleteuser_login]: self.client.post(login_url, login_dict) response = self.client.get(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) self.client.get(reverse('admin:logout')) for login_dict in [self.joepublic_login, self.no_username_login]: self.client.post(login_url, login_dict) response = self.client.get(change_url_1, follow=True) self.assertEqual(response.status_code, 200) 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.assertEqual(response.status_code, 200) self.assertContains(response, 'login-form') response = self.client.get(change_url_2, follow=True) self.assertEqual(response.status_code, 200) 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.assertEqual(response.status_code, 200) self.assertContains(response, 'login-form') self.client.get(reverse('admin:logout')) 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=(1,)) # add user should not be able to delete articles self.client.login(**self.adduser_login) 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.login(**self.deleteuser_login) response = self.client.get(reverse('admin:admin_views_section_delete', args=(1,))) self.assertContains(response, "Multiline
html
content
', 3) self.assertContains(response, '
Some help text for the title (with unicode ŠĐĆŽćžšđ)
', html=True) self.assertContains(response, 'Some help text for the content (with unicode ŠĐĆŽćžšđ)
', html=True) self.assertContains(response, 'Some help text for the date (with unicode ŠĐĆŽćžšđ)
', html=True) p = Post.objects.create(title="I worked on readonly_fields", content="Its good stuff") response = self.client.get(reverse('admin:admin_views_post_change', args=(p.pk,))) self.assertContains(response, "%d amount of cool" % p.pk) def test_readonly_post(self): data = { "title": "Django Got Readonly Fields", "content": "This is an incredible development.", "link_set-TOTAL_FORMS": "1", "link_set-INITIAL_FORMS": "0", "link_set-MAX_NUM_FORMS": "0", } response = self.client.post(reverse('admin:admin_views_post_add'), data) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 1) p = Post.objects.get() self.assertEqual(p.posted, datetime.date.today()) data["posted"] = "10-8-1990" # some date that's not today response = self.client.post(reverse('admin:admin_views_post_add'), data) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 2) p = Post.objects.order_by('-id')[0] self.assertEqual(p.posted, datetime.date.today()) def test_readonly_manytomany(self): "Regression test for #13004" response = self.client.get(reverse('admin:admin_views_pizza_add')) self.assertEqual(response.status_code, 200) def test_user_password_change_limited_queryset(self): su = User.objects.filter(is_superuser=True)[0] response = self.client.get(reverse('admin2:auth_user_password_change', args=(su.pk,))) self.assertEqual(response.status_code, 404) def test_change_form_renders_correct_null_choice_value(self): """ Regression test for #17911. """ choice = Choice.objects.create(choice=None) response = self.client.get(reverse('admin:admin_views_choice_change', args=(choice.pk,))) self.assertContains(response, 'No opinion
', html=True) self.assertNotContains(response, '(None)
') def test_readonly_backwards_ref(self): """ Regression test for #16433 - backwards references for related objects broke if the related field is read-only due to the help_text attribute """ topping = Topping.objects.create(name='Salami') pizza = Pizza.objects.create(name='Americano') pizza.toppings.add(topping) response = self.client.get(reverse('admin:admin_views_topping_add')) self.assertEqual(response.status_code, 200) def test_readonly_field_overrides(self): """ Regression test for #22087 - ModelForm Meta overrides are ignored by AdminReadonlyField """ p = FieldOverridePost.objects.create(title="Test Post", content="Test Content") response = self.client.get(reverse('admin:admin_views_fieldoverridepost_change', args=(p.pk,))) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Overridden help text for the date
') self.assertContains(response, '', html=True) self.assertNotContains(response, "Some help text for the date (with unicode ŠĐĆŽćžšđ)") @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF="admin_views.urls") class LimitChoicesToInAdminTest(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def test_limit_choices_to_as_callable(self): """Test for ticket 2445 changes to admin.""" threepwood = Character.objects.create( username='threepwood', last_action=datetime.datetime.today() + datetime.timedelta(days=1), ) marley = Character.objects.create( username='marley', last_action=datetime.datetime.today() - datetime.timedelta(days=1), ) response = self.client.get(reverse('admin:admin_views_stumpjoke_add')) # The allowed option should appear twice; the limited option should not appear. self.assertContains(response, threepwood.username, count=2) self.assertNotContains(response, marley.username) @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF="admin_views.urls") class RawIdFieldsTest(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def test_limit_choices_to(self): """Regression test for 14880""" actor = Actor.objects.create(name="Palin", age=27) Inquisition.objects.create(expected=True, leader=actor, country="England") Inquisition.objects.create(expected=False, leader=actor, country="Spain") response = self.client.get(reverse('admin:admin_views_sketch_add')) # Find the link m = re.search(br']* id="lookup_id_inquisition"', response.content) self.assertTrue(m) # Got a match popup_url = m.groups()[0].decode().replace("&", "&") # Handle relative links popup_url = urljoin(response.request['PATH_INFO'], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step also tests integers, strings and booleans in the # lookup query string; in model we define inquisition field to have a # limit_choices_to option that includes a filter on a string field # (inquisition__actor__name), a filter on an integer field # (inquisition__actor__age), and a filter on a boolean field # (inquisition__expected). response2 = self.client.get(popup_url) self.assertContains(response2, "Spain") self.assertNotContains(response2, "England") def test_limit_choices_to_isnull_false(self): """Regression test for 20182""" Actor.objects.create(name="Palin", age=27) Actor.objects.create(name="Kilbraken", age=50, title="Judge") response = self.client.get(reverse('admin:admin_views_sketch_add')) # Find the link m = re.search(br']* id="lookup_id_defendant0"', response.content) self.assertTrue(m) # Got a match popup_url = m.groups()[0].decode().replace("&", "&") # Handle relative links popup_url = urljoin(response.request['PATH_INFO'], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step tests field__isnull=0 gets parsed correctly from the # lookup query string; in model we define defendant0 field to have a # limit_choices_to option that includes "actor__title__isnull=False". response2 = self.client.get(popup_url) self.assertContains(response2, "Kilbraken") self.assertNotContains(response2, "Palin") def test_limit_choices_to_isnull_true(self): """Regression test for 20182""" Actor.objects.create(name="Palin", age=27) Actor.objects.create(name="Kilbraken", age=50, title="Judge") response = self.client.get(reverse('admin:admin_views_sketch_add')) # Find the link m = re.search(br']* id="lookup_id_defendant1"', response.content) self.assertTrue(m) # Got a match popup_url = m.groups()[0].decode().replace("&", "&") # Handle relative links popup_url = urljoin(response.request['PATH_INFO'], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step tests field__isnull=1 gets parsed correctly from the # lookup query string; in model we define defendant1 field to have a # limit_choices_to option that includes "actor__title__isnull=True". response2 = self.client.get(popup_url) self.assertNotContains(response2, "Kilbraken") self.assertContains(response2, "Palin") @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF="admin_views.urls") class UserAdminTest(TestCase): """ Tests user CRUD functionality. """ fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def 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.order_by('-id')[0] 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.order_by('-id')[0] 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_password_mismatch(self): response = self.client.post(reverse('admin:auth_user_add'), { 'username': 'newuser', 'password1': 'newpassword', 'password2': 'mismatch', }) self.assertEqual(response.status_code, 200) adminform = response.context['adminform'] self.assertNotIn('password', adminform.form.errors) self.assertEqual(adminform.form.errors['password2'], ["The two password fields didn't match."]) def test_user_fk_add_popup(self): """User addition through a FK popup should return the appropriate JavaScript response.""" response = self.client.get(reverse('admin:admin_views_album_add')) self.assertEqual(response.status_code, 200) self.assertContains(response, reverse('admin:auth_user_add')) self.assertContains(response, 'class="related-widget-wrapper-link add-related" id="add_id_owner"') response = self.client.get(reverse('admin:auth_user_add') + '?_popup=1') self.assertEqual(response.status_code, 200) self.assertNotContains(response, 'name="_continue"') self.assertNotContains(response, 'name="_addanother"') data = { 'username': 'newuser', 'password1': 'newpassword', 'password2': 'newpassword', '_popup': '1', '_save': '1', } response = self.client.post(reverse('admin:auth_user_add') + '?_popup=1', data, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, 'dismissAddRelatedObjectPopup') def test_user_fk_change_popup(self): """User change through a FK popup should return the appropriate JavaScript response.""" response = self.client.get(reverse('admin:admin_views_album_add')) self.assertEqual(response.status_code, 200) self.assertContains(response, reverse('admin:auth_user_change', args=('__fk__',))) self.assertContains(response, 'class="related-widget-wrapper-link change-related" id="change_id_owner"') user = User.objects.get(username='changeuser') url = reverse('admin:auth_user_change', args=(user.pk,)) + '?_popup=1' response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertNotContains(response, 'name="_continue"') self.assertNotContains(response, 'name="_addanother"') data = { 'username': 'newuser', 'password1': 'newpassword', 'password2': 'newpassword', 'last_login_0': '2007-05-30', 'last_login_1': '13:20:10', 'date_joined_0': '2007-05-30', 'date_joined_1': '13:20:10', '_popup': '1', '_save': '1', } response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, 'dismissChangeRelatedObjectPopup') def test_user_fk_delete_popup(self): """User deletion through a FK popup should return the appropriate JavaScript response.""" response = self.client.get(reverse('admin:admin_views_album_add')) self.assertEqual(response.status_code, 200) self.assertContains(response, reverse('admin:auth_user_delete', args=('__fk__',))) self.assertContains(response, 'class="related-widget-wrapper-link change-related" id="change_id_owner"') user = User.objects.get(username='changeuser') url = reverse('admin:auth_user_delete', args=(user.pk,)) + '?_popup=1' response = self.client.get(url) self.assertEqual(response.status_code, 200) data = { 'post': 'yes', '_popup': '1', } response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, 'dismissDeleteRelatedObjectPopup') def test_save_add_another_button(self): user_count = User.objects.count() response = self.client.post(reverse('admin:auth_user_add'), { 'username': 'newuser', 'password1': 'newpassword', 'password2': 'newpassword', '_addanother': '1', }) new_user = User.objects.order_by('-id')[0] self.assertRedirects(response, reverse('admin:auth_user_add')) self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) def test_user_permission_performance(self): u = User.objects.all()[0] # Don't depend on a warm cache, see #17377. ContentType.objects.clear_cache() with self.assertNumQueries(10): response = self.client.get(reverse('admin:auth_user_change', args=(u.pk,))) self.assertEqual(response.status_code, 200) def test_form_url_present_in_context(self): u = User.objects.all()[0] response = self.client.get(reverse('admin3:auth_user_password_change', args=(u.pk,))) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['form_url'], 'pony') @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF="admin_views.urls") class GroupAdminTest(TestCase): """ Tests group CRUD functionality. """ fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def test_save_button(self): group_count = Group.objects.count() response = self.client.post(reverse('admin:auth_group_add'), { 'name': 'newgroup', }) Group.objects.order_by('-id')[0] self.assertRedirects(response, reverse('admin:auth_group_changelist')) self.assertEqual(Group.objects.count(), group_count + 1) def test_group_permission_performance(self): g = Group.objects.create(name="test_group") # Ensure no queries are skipped due to cached content type for Group. ContentType.objects.clear_cache() with self.assertNumQueries(8): response = self.client.get(reverse('admin:auth_group_change', args=(g.pk,))) self.assertEqual(response.status_code, 200) @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF="admin_views.urls") class CSSTest(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): self.client.login(username='super', password='secret') def test_field_prefix_css_classes(self): """ Ensure that fields have a CSS class name with a 'field-' prefix. Refs #16371. """ 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, '