class TestCflatpagesAdmin(TestCase): def setUp(self): self.site = AdminSite() def test_category_admin(self): """ Category admin """ self.assertIsNone(self.site.register(models.Category, admin.CategoryAdmin)) def test_page_admin(self): """ Page admin """ self.assertIsNone(self.site.register(models.CFlatPage, admin.CategorizedFlatPageAdmin)) @override_settings() def test_page_settings_admin(self): """ Page admin """ settings.INSTALLED_APPS = settings.INSTALLED_APPS + ["ckeditor"] self.assertIsNone(self.site.register(models.CFlatPage, admin.CategorizedFlatPageAdmin)) def tearDown(self): pass
def test_autocomplete_is_onetoone(self): class UserAdmin(ModelAdmin): search_fields = ('name',) class Admin(ModelAdmin): autocomplete_fields = ('best_friend',) site = AdminSite() site.register(User, UserAdmin) self.assertIsValid(Admin, ValidationTestModel, admin_site=site)
def test_autocomplete_is_valid(self): class SearchFieldsAdmin(ModelAdmin): search_fields = 'name' class AutocompleteAdmin(ModelAdmin): autocomplete_fields = ('featuring',) site = AdminSite() site.register(Band, SearchFieldsAdmin) self.assertIsValid(AutocompleteAdmin, Song, admin_site=site)
class StatsAdminTests(TestCase): def setUp(self): self.admin_site = AdminSite() patch_admin(self.admin_site) self.factory = RequestFactory() def test_modelstats_overview_called(self): """Test that the overview function on the ModelStats object is called by the overview function on the admin site. """ class TestModelStats(ModelStats): slug = 'unique_slug' self.admin_site.register_stats(TestModel, TestModelStats) with patch.object(TestModelStats, 'overview') as overview: eq_(overview.called, False) self.admin_site.overview(self.factory.get('/test'), 'unique_slug') eq_(overview.called, True) def test_unique_slugs(self): """Test that the admin site generates unique slugs for multiple ModelStats that have identical slugs. """ class TestModelStats(ModelStats): slug = 'unique_slug' self.admin_site.register_stats(TestModel, TestModelStats) class TestModelStats2(ModelStats): slug = 'unique_slug' self.admin_site.register_stats(TestModel, TestModelStats2) # If slugs were identical, there would be only 1 stat here. eq_(len(self.admin_site.stats), 2)
def display_login_form(request, error_message='', extra_context=None): extra_context = extra_context or {} extra_context['openid_path'] = openid_path return AdminSite.display_login_form( bind_to_me, request, error_message, extra_context )
def setUp(self): self.band = Band.objects.create( name='The Doors', bio='', sign_date=date(1965, 1, 1), ) self.site = AdminSite()
def lazy_registration(self): # First, directly handle models we don't want at all, # as per the ``ADMIN_REMOVAL`` setting. for model in getattr(settings, "ADMIN_REMOVAL", []): try: model = tuple(model.rsplit(".", 1)) exec("from %s import %s" % model) except ImportError: pass else: try: AdminSite.unregister(self, eval(model[1])) except NotRegistered: pass # Call register/unregister. for name, deferred_args, deferred_kwargs in self._deferred: getattr(AdminSite, name)(self, *deferred_args, **deferred_kwargs)
def test_validation_only_runs_in_debug(self): # Ensure validation only runs when DEBUG = True with override_settings(DEBUG=True): class ValidationTestModelAdmin(ModelAdmin): raw_id_fields = 10 site = AdminSite() six.assertRaisesRegex(self, ImproperlyConfigured, "'ValidationTestModelAdmin.raw_id_fields' must be a list or tuple.", site.register, ValidationTestModel, ValidationTestModelAdmin, ) with override_settings(DEBUG=False): site = AdminSite() site.register(ValidationTestModel, ValidationTestModelAdmin)
def test_autocomplete_e040(self): class NoSearchFieldsAdmin(ModelAdmin): pass class AutocompleteAdmin(ModelAdmin): autocomplete_fields = ('featuring',) site = AdminSite() site.register(Band, NoSearchFieldsAdmin) self.assertIsInvalid( AutocompleteAdmin, Song, msg=( 'NoSearchFieldsAdmin must define "search_fields", because ' 'it\'s referenced by AutocompleteAdmin.autocomplete_fields.' ), id='admin.E040', invalid_obj=AutocompleteAdmin, admin_site=site, )
def test_validation_only_runs_in_debug(self): # Ensure validation only runs when DEBUG = True try: settings.DEBUG = True class ValidationTestModelAdmin(ModelAdmin): raw_id_fields = 10 site = AdminSite() self.assertRaisesRegexp( ImproperlyConfigured, "'ValidationTestModelAdmin.raw_id_fields' must be a list or tuple.", site.register, ValidationTestModel, ValidationTestModelAdmin, ) finally: settings.DEBUG = False site = AdminSite() site.register(ValidationTestModel, ValidationTestModelAdmin)
def lazy_registration(self): # First pick up any admin classes registered via decorator to the # default admin site. for model, admin in default_site._registry.items(): self._deferred.append(("register", (model, admin.__class__), {})) # Call register/unregister. for name, args, kwargs in self._deferred: try: getattr(AdminSite, name)(self, *args, **kwargs) except (AlreadyRegistered, NotRegistered): pass # Then handle models we don't want at all, # as per the ``ADMIN_REMOVAL`` setting. for model in getattr(settings, "ADMIN_REMOVAL", []): try: model = tuple(model.rsplit(".", 1)) exec("from %s import %s" % model) except ImportError: pass else: try: AdminSite.unregister(self, eval(model[1])) except NotRegistered: pass
def test_save_model(self): request = self.factory.get('/madeup/url') site = AdminSite() digwork = DigitizedWork(source_id='njp.32101013082597') form = Mock() change = False digadmin = DigitizedWorkAdmin(DigitizedWork, site) # initially created, so work should just be saved, no flags set digadmin.save_model(request, digwork, form, change) saved_work = DigitizedWork.objects.get(source_id=digwork.source_id) assert saved_work == digwork assert saved_work.protected_fields == ProtectedWorkFieldFlags.no_flags saved_work.title = 'Test Title' saved_work.enumcron = '0001' change = True # saved work should now set the flags for the altered fields digadmin.save_model(request, saved_work, form, change) new_work = DigitizedWork.objects.get(pk=saved_work.pk) assert new_work.protected_fields == \ ProtectedWorkFieldFlags.title | ProtectedWorkFieldFlags.enumcron
def test_list_collections(self): # set up preliminary objects needed to test an admin site object site = AdminSite() digadmin = DigitizedWorkAdmin(DigitizedWork, site) # no collections should return an empty string digwork = DigitizedWork.objects.create(source_id='njp.32101013082597') coll_list = digadmin.list_collections(digwork) assert coll_list == '' # create two collections and set them on digwork Z = Collection.objects.create(name='Z Collection') A = Collection.objects.create(name='A Collection') C = Collection.objects.create(name='C Collection') digwork.collections.set([Z, A, C]) # should now return an alphabetized, comma separated list coll_list = digadmin.list_collections(digwork) assert coll_list == 'A Collection, C Collection, Z Collection'
def setUp(self): self.username = "******" self.email = "*****@*****.**" self.student_id = "bogus_student_id" self.course_id = "bogus_course_id" self.stack_name = "bogus_stack_name" self.provider = "bogus_provider" self.providers = [{ "name": "provider1", "capacity": 1, "template": "tmpl1", "environment": "env1" }, { "name": "provider2", "capacity": 2, "template": "tmpl2", "environment": "env2" }, { "name": "provider3", "capacity": -1, "template": "tmpl3", "environment": "env3" }] self.user = User.objects.create_user(self.username, self.email, "password") self.anonymous_user_id = AnonymousUserId.objects.create( user=self.user, anonymous_user_id=self.student_id) self.stack = Stack.objects.create(student_id=self.student_id, course_id=self.course_id, name=self.stack_name, learner=self.user, status="CREATE_COMPLETE", provider=self.provider, providers=self.providers) self.stack_admin = StackAdmin(Stack, AdminSite()) self.request = HttpRequest() self.admin = User.objects.create_superuser('admin', '*****@*****.**', 'password') self.client = Client() self.client.login(username='******', password='******')
def setUp(self): self.user1 = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.organization = Organization.objects.create(name="My Org") self.org_user = OrganizationUser.objects.create( user=self.user1, organization=self.organization) self.org_owner = OrganizationOwner.objects.create( organization=self.organization, organization_user=self.org_user) self.phone = Phone.objects.create(phone_number="+19783284466", user=self.user1) self.button1 = Button.objects.create(serial_number="1111222233334444", user=self.user1) self.button_action1 = ButtonAction.objects.create( name="Call User1", target_user=self.phone) self.button1.single_press_actions.add(self.button_action1) self.button1.double_press_actions.add( ButtonAction.objects.create(name="Text User1", target_user=self.phone)) # Other People's Stuff self.user2 = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.not_my_phone = Phone.objects.create(phone_number="+12223334444", user=self.user2) self.not_my_organization = Organization.objects.create( name='Not My Org') self.someone_elses_button = Button.objects.create( serial_number="5555666677778888", user=self.user2) self.someone_elses_action = ButtonAction.objects.create( name="Not Mine", type="call", message="hi", target_user=self.not_my_phone) # Prep site and request stuff self.superuser_request = MockRequest() self.superuser_request.user = MockSuperUser() self.site = AdminSite()
def setUp(self): self.factory = RequestFactory() self.site = AdminSite() self.ma = admin.ModelAdmin(Theme, self.site) self.t1 = Theme.objects.create( name="Test1", description="Test Description", default_theme=True, active_theme=True, title="Test Title", tagline="Test Tagline", running_hex="ffffff", running_text_hex="ffffff", running_link_hex="ffffff", pb_text="Test Powered By Text", pb_link="http://boundlessgeo.com/", docs_text="Documentation", docs_link="/static/docs/html/index.html", background_logo="theme/img/default-background.png", primary_logo="theme/img/default-primary-logo.png", banner_logo="theme/img/default-banner-logo.png") self.t1.save() self.t2 = Theme.objects.create( name="Test2", description="Test Description", default_theme=False, active_theme=True, title="Test Title", tagline="Test Tagline", running_hex="ffffff", running_text_hex="ffffff", running_link_hex="ffffff", pb_text="Test Powered By Text", pb_link="http://boundlessgeo.com/", docs_text="Documentation", docs_link="https://boundlessgeo.github.io/" "exchange-documentation/", background_logo=None, primary_logo=None, banner_logo=None) self.t2.save()
def test_image_resubmit_admin(self): testadmin = self.TestImageAdmin(model=self.TestImageModel, admin_site=AdminSite()) with open(self.temporary_image.name, 'rb') as fo: request = self.factory.post('/admin/example/', {'admin_upload_image': fo}) request.user = self.user request._dont_enforce_csrf_checks = True response = testadmin.add_view(request) form = response.context_data['adminform'].form resubmit_field, resubmit_value = self.get_resubmit_field( form, 'admin_upload_image') data = {resubmit_field: resubmit_value} resubmit_req = self.factory.post('/admin/example/', data) resubmit_req.user = self.user resubmit_req._dont_enforce_csrf_checks = True resubmit_resp = testadmin.add_view(resubmit_req) form = resubmit_resp.context_data['adminform'].form self.assertEqual(len(form.errors), 1) uploaded_image = form.cleaned_data['admin_upload_image'] self.assertEqual(uploaded_image.read(), PNG)
def test_image_resubmit_save_admin(self): testadmin = self.TestImageAdmin(model=self.TestImageModel, admin_site=AdminSite()) with open(self.temporary_image.name, 'rb') as fo: request = self.factory.post('/admin/example/', {'admin_upload_image': fo}) request.user = self.user request._dont_enforce_csrf_checks = True response = testadmin.add_view(request) form = response.context_data['adminform'].form resubmit_field, resubmit_value = self.get_resubmit_field( form, 'admin_upload_image') data = {'admin_name': "Sample", resubmit_field: resubmit_value} resubmit_req = self.factory.post('/admin/example/', data) setattr(resubmit_req, 'session', 'session') messages = FallbackStorage(resubmit_req) setattr(resubmit_req, '_messages', messages) resubmit_req.user = self.user resubmit_req._dont_enforce_csrf_checks = True saved_obj = testadmin.add_view(resubmit_req) self.assertEqual(saved_obj.admin_upload_image.read(), PNG)
def test_test_case_filter_queryset_with_value(self): """ Check the case where filtering is required with version '2' Only variables linked to this version should be returned """ step_reference_admin = StepReferenceAdmin(model=StepReference, admin_site=AdminSite()) request = MockRequest() test_case_filter = TestCaseFilter(request, {'test_case_id': 5}, StepReference, step_reference_admin) queryset = test_case_filter.queryset( request=request, queryset=StepReference.objects.all()) # check only variables without version are displayed self.assertEqual( len(queryset), len( StepReference.objects.filter( stepResult__testCase__testCase__id=5)))
def test_target_group_clean_required_fields_for_case(self): target_group = create_target_group( name="familieafdelingen", required_fields_for_case="district,effort_step", ) site = AdminSite() request = MockRequest() target_group_admin = TargetGroupAdmin(TargetGroup, site) target_group_form_class = target_group_admin.get_form( request, target_group) target_group_data = { "name": "familieafdelingen", "required_fields_for_case": ["district", "effort_step"], } target_group_form = target_group_form_class(target_group_data) self.assertTrue(target_group_form.is_valid()) self.assertEqual( target_group_form.cleaned_data["required_fields_for_case"], "district,effort_step", )
def setUp(self): from opensubmit.admin.submission import SubmissionAdmin super(SubmissionModelAdminTestCase, self).setUp() # Tutor is already logged in, we need an additional admin self.admin = create_user(admin_dict) # Prepare assignments self.course = create_course(self.admin, self.user) self.grading_scheme = create_pass_fail_grading() self.assign1 = create_open_assignment(self.course, self.grading_scheme) self.assign2 = create_soft_passed_assignment(self.course, self.grading_scheme) self.assign3 = create_validated_assignment_with_archive( self.course, self.grading_scheme) self.all_assignments = [self.assign1, self.assign2, self.assign3] # Prepare submissions self.sub1 = create_submission(self.user, self.assign1) self.sub2 = create_submission(self.user, self.assign2) self.sub3 = create_validated_submission(self.user, self.assign3) self.all_submissions = [self.sub1, self.sub2, self.sub3] self.submadm = SubmissionAdmin(Submission, AdminSite())
def test_admin(self): admin = InvalidationAdmin(model=Invalidation, admin_site=AdminSite()) request = RequestFactory() request.user = User.objects.create(username='******') form = admin.get_form(request=request) self.assertEqual(form.declared_fields['invalid_tags'].initial, None) self.assertEqual(form.declared_fields['invalid_tags'].disabled, False) self.cache_test() obj = Invalidation.objects.create(tags='test') form = admin.get_form(request=request, obj=obj) self.assertEqual(form.declared_fields['invalid_tags'].initial, ['test']) self.assertEqual(form.declared_fields['invalid_tags'].disabled, True) obj2 = Invalidation(id=999) form = admin.get_form(request=request, obj=None)({'pattern': 'aaa', 'invalid_tags': ['test']}) self.assertTrue(form.is_valid()) admin.save_model(request, obj2, form, False) self.assertEqual(Invalidation.objects.get(id=999).tags, 'test')
def test_object_link(self): admin = LogEntryAdmin(LogEntry, AdminSite()) deleted = LogEntry(object_repr='OBJ_REPR', action_flag=DELETION) self.assertEquals(admin.object_link(deleted), 'OBJ_REPR') created = LogEntry( content_type_id=ContentType.objects.get_for_model(User).id, action_flag=ADDITION, object_id=self.user.id, object_repr='OBJ_REPR' ) self.assertIn('OBJ_REPR', admin.object_link(created)) self.assertIn('<a href="', admin.object_link(created)) no_reverse = LogEntry( content_type_id=ContentType.objects.get(model='session').id, action_flag=CHANGE, object_id=5, object_repr='OBJ_REPR' ) self.assertEquals(admin.object_link(no_reverse), 'OBJ_REPR')
def test_paypal_block_admin_display(self): user = mommy.make_recipe('booking.user', first_name='Test', last_name='User') block = mommy.make_recipe('booking.block_5', user=user) pptrans = helpers.create_block_paypal_transaction(block.user, block) ppblock_admin = admin.PaypalBlockTransactionAdmin( PaypalBlockTransaction, AdminSite()) ppblock_query = ppblock_admin.get_queryset(None)[0] self.assertEqual(ppblock_admin.get_block_id(ppblock_query), block.id) self.assertEqual(ppblock_admin.get_user(ppblock_query), 'Test User') self.assertEqual(ppblock_admin.get_blocktype(ppblock_query), block.block_type) self.assertEqual(ppblock_admin.cost(ppblock_query), u"\u00A3{:.2f}".format(block.block_type.cost)) self.assertEqual(ppblock_admin.block_start(ppblock_query), block.start_date.strftime('%d %b %Y, %H:%M')) self.assertEqual(ppblock_admin.block_expiry(ppblock_query), block.expiry_date.strftime('%d %b %Y, %H:%M'))
def test_admin(self): """ unittest for ContentReleaseAdmin """ # check base_realse readonly when update ContentRelease site = AdminSite() content_release_admin = ContentReleaseAdmin(ContentRelease, site) content_release = ContentRelease( version='0.0.1', title='test1', site_code='site1', status=0, ) content_release.save() self.assertEqual(content_release_admin.get_readonly_fields(None, None), []) self.assertEqual( content_release_admin.get_readonly_fields(None, content_release), ['base_release'], )
def test_filter_queryset( mocker, admin_model, model, filter_model, mocker_path, action_suggestion, # pylint: disable=unused-argument quote_suggestion, # pylint: disable=unused-argument ): request = get_generic_request() filter_instance = filter_model( request=request, params={}, model=model, model_admin=admin_model(model=model, admin_site=AdminSite()), ) mocker.patch(mocker_path, return_value="Test") queryset = filter_instance.queryset(request=request, queryset=model.objects.all()) assert not queryset.exists()
def test_admin_registration_lookup(self): key_day, name = date.today(), 'sess1' publish = key_day - timedelta(days=7 * 3 + 1) sess1 = Session.objects.create(name=name, key_day_date=key_day, max_day_shift=6, publish_date=publish) subj = Subject.objects.create(version=Subject.VERSION_CHOICES[0][0], name="test_subj") kwargs = {'subject': subj, 'session': sess1, 'start_time': time(19, 0)} classoffers = [ ClassOffer.objects.create(class_day=k, **kwargs) for k, v in ClassOffer.DOW_CHOICES if k % 2 ] expected_lookup = ((k, v) for k, v in ClassOffer.DOW_CHOICES if k % 2) password = environ.get('SUPERUSER_PASS', '') admin_user_email = environ.get('SUPERUSER_EMAIL', settings.ADMINS[0][1]) user = User.objects.create_superuser(admin_user_email, admin_user_email, password) user.first_name = "test_super" user.last_name = "test_user" user.save() student = getattr(user, self.student_profile_attribute, None) registrations = [ Registration.objects.create(student=student, classoffer=ea) for ea in classoffers ] current_admin = RegistrationAdmin(model=Registration, admin_site=AdminSite()) day_filter = ClassDayListFilter(request, {}, Registration, current_admin) lookup = day_filter.lookups(request, current_admin) self.assertEqual(len(registrations), 3) self.assertEqual(Registration.objects.count(), 3) self.assertIsInstance(lookup, GeneratorType) self.assertEqual(list(expected_lookup), list(lookup))
def test_impersonatelog_admin_impersonator_filter(self): self.assertFalse(ImpersonationLog.objects.exists()) self._impersonate_helper('user1', 'foobar', 4) self.client.get(reverse('impersonate-stop')) self._impersonate_helper('user2', 'foobar', 4) self.client.get(reverse('impersonate-stop')) model_admin = ImpersonationLogAdmin(ImpersonationLog, AdminSite()) _filter = ImpersonatorFilter( None, {}, ImpersonationLog, model_admin, ) qs = _filter.queryset(None, ImpersonationLog.objects.all()) self.assertEqual(qs.count(), 2) _filter = ImpersonatorFilter( None, {'impersonator': '1'}, ImpersonationLog, model_admin, ) qs = _filter.queryset(None, ImpersonationLog.objects.all()) self.assertEqual(qs.count(), 1) _filter = ImpersonatorFilter( None, {'impersonator': '2'}, ImpersonationLog, model_admin, ) qs = _filter.queryset(None, ImpersonationLog.objects.all()) self.assertEqual(qs.count(), 1) # Check that both user1 and user2 are in the lookup options opts = [(_id, name) for _id, name in _filter.lookups(None, model_admin)] self.assertTrue(1 in [x[0] for x in opts]) self.assertTrue(2 in [x[0] for x in opts])
def test_has_valid_migration_options(self): site = AdminSite() product_admin = admin.ProductAdmin(models.Product, site) obj = mixer.blend( "productdb.Product", name="Product", eox_update_time_stamp=None ) result = product_admin.has_migration_options(obj) expected = False assert result == expected mixer.blend( "productdb.ProductMigrationOption", product=obj, migration_source=ProductMigrationSource.objects.create(name="test") ) result = product_admin.has_migration_options(obj) expected = True assert result == expected
def setUp(self): self.user = User.objects.create_user(username="******", email="*****@*****.**", password="******") issuer = Issuer.objects.create(name="Université Paul-Valéry", url="https://www.univ-montp3.fr/", email="*****@*****.**", location="Montpellier, France") tag = Tag.objects.create(name="Software Development") self.event = Event(issuer=issuer, name="Bootcamp Agile", url="http://www.bootcamp-agile.com", diploma_type="B", location="Montpellier, France") self.event_admin = EventAdmin(model=Event, admin_site=AdminSite()) self.event_admin.save_model(obj=self.event, request=MockRequest(user=self.user), form=None, change=False) self.event.tags.add(tag.id)
def test_lockuser_html_heading(self): """ Does the AccessTime change list page display LockUsers as links to their change pages? """ ata = AccessTimeAdmin(AccessTime, AdminSite()) all_at = AccessTime.objects.all() some_at = all_at[0:10] # using the actual method for at in some_at: compare_string = "<a href='../lockuser/%d/'>%s</a>" % ( at.lockuser.id, at.lockuser) self.assertEqual(ata.lockuser_html_heading(at), compare_string) # looking at the page, i.e. more functional response = self.client.get( "/lockadmin/rfid_lock_management/accesstime/") for lu in LockUser.objects.all(): if lu.get_last_access_time(): link = "<a href='../lockuser/%d/'>%s</a>" % (lu.id, lu) self.assertIn(link, response.content)
def setUp(self): self.initial_user1_username = str(uuid.uuid4()) self.initial_user_2_username = str(uuid.uuid4()) club = Club.objects.create(name='Klub', code=15545) self.user_1 = RushUser.objects.create_user( email='*****@*****.**', first_name='Łukasz', last_name='Ślązak', organization_name='School', organization_address='Address', password='******', username=self.initial_user1_username, unit=club) self.user_2 = RushUser.objects.create_user( email='*****@*****.**', first_name='Adam', last_name='Ślowacki', organization_name='School', organization_address='Address', password='******', username=self.initial_user_2_username, unit=club) self.user_3 = RushUser.objects.create_user( email='*****@*****.**', first_name='Ewa', last_name='Kowalska', organization_name='School', organization_address='Address', password='******', username='******', unit=club) self.request = HttpRequest() self.request.META['SERVER_NAME'] = '127.0.0.1' self.request.META['SERVER_PORT'] = '8000' self.app_admin = RushUserAdmin(RushUser, AdminSite()) self.user_3.is_active = True
def test_customer_deleting_is_possible_only_if_related_project_is_removed(self): site = AdminSite() model_admin = structure_admin.CustomerAdmin(structure_models.Customer, site) project = factories.ProjectFactory(customer=self.customer) request = MockRequest() queryset = structure_models.Customer.objects.filter(pk=self.customer.id) self.assertRaises( ProtectedError, model_admin.delete_queryset, request, queryset ) project_id = project.id project.delete() # A project exists in DB because we use soft-delete for projects. self.assertTrue( structure_models.Project.structure_objects.filter(pk=project_id).exists() ) model_admin.delete_queryset(request, queryset) self.assertRaises( structure_models.Customer.DoesNotExist, self.customer.refresh_from_db )
def test_ta_add_new_ta(client, STC, base_db_setup): ''' Create one teaching assistant, 5 courses and 3 assignments for each course. The TA is added to courses 1, 3, 5 and should see only those assignments ''' (super_user, ta, user, course, _) = base_db_setup client.login(username=user.username, password='******') response = client.get('/admin/') STC.assertRedirects(response, '/admin/login/?next=/admin/') request = MockObject() request.user = super_user form = MockObject() form.changed_data = ["teaching_assistants"] form.cleaned_data = {"teaching_assistants": [user, ta]} test_course_admin = CourseAdmin(model=Course, admin_site=AdminSite()) test_course_admin.save_model( obj=course, request=request, form=form, change=True, ) course.teaching_assistants.add(user) course.save() # Now you should be able to access it response = client.get('/admin/') assert response.status_code == 200 response = client.get('/admin/interface/assignment/') # There is only one assignment added in the conftest for a course assert len(response.context['results']) == 1
def setUp(self): """ Test case setup """ self.user = User.objects.create_user('test_user', '*****@*****.**', 'foo') self.table_entry = CourseCreator(user=self.user) self.table_entry.save() self.admin = User.objects.create_user('Mark', '*****@*****.**', 'foo') self.admin.is_staff = True self.request = HttpRequest() self.request.user = self.admin self.creator_admin = CourseCreatorAdmin(self.table_entry, AdminSite()) self.studio_request_email = '*****@*****.**' self.enable_creator_group_patch = { "ENABLE_CREATOR_GROUP": True, "STUDIO_REQUEST_EMAIL": self.studio_request_email }
def setUp(self): super(TestProjectRefundAdmin, self).setUp() self.site = AdminSite() self.request_factory = RequestFactory() self.init_projects() self.project_admin = ProjectAdmin(Project, self.site) self.project = ProjectFactory.create( status=ProjectPhase.objects.get(slug='closed'), ) self.order = OrderFactory.create(status='success') DonationFactory.create( project=self.project, order=self.order, amount=Money(100, 'EUR'), ) self.request = self.request_factory.post('/', data={'confirm': True}) self.request.user = MockUser(['payments.refund_orderpayment'])
def setUp(self): self.factory = RequestFactory() user_model = get_user_model() self.user = user_model.objects.create_superuser(email="*****@*****.**", password="******") self.contribution_admin = ContributionAdmin(Contribution, AdminSite()) self.organization = OrganizationFactory( default_payment_provider="stripe") self.contrib_score_2 = ContributionFactory( status=ContributionStatus.FLAGGED, bad_actor_score=2, organization=self.organization, payment_provider_used="Stripe", ) self.contrib_score_4 = ContributionFactory( status=ContributionStatus.FLAGGED, bad_actor_score=4, organization=self.organization, payment_provider_used="Stripe", )
def setUp(self): """ Create a device at the fourth time step. The current token is 154567. """ try: self.admin = self.create_user('admin', 'password', email='*****@*****.**', is_staff=True) except IntegrityError: self.skipTest("Unable to create the test user.") else: self.device = self.admin.totpdevice_set.create( key='2a2bbba1092ffdd25a328ad1a0a5f5d61d7aacc4', step=30, t0=int(time() - (30 * 3)), digits=6, tolerance=0, drift=0) self.device_admin = TOTPDeviceAdmin(TOTPDevice, AdminSite()) self.get_request = RequestFactory().get('/') self.get_request.user = self.admin
def test_fieldsets(self): ma = SettingAdmin(model=Setting, admin_site=AdminSite()) self.assertEqual( ma.get_fieldsets(request), (( None, { "classes": ("wide", ), "fields": ("value_type", "name", "description"), }, ), ), ) self.assertEqual( ma.get_fieldsets(request, self._setting_obj), (( None, { "classes": ("wide", ), "fields": ("name", "description", "value_string"), }, ), ), )
def test_init_sets_start_date_and_rate(self): request = MockRequest() site = AdminSite() rate_admin = RateAdmin(Rate, site) today = date.today() tomorrow = today + timedelta(days=1) two_days_from_now = tomorrow + timedelta(days=1) rate = create_rate() create_rate_per_date(rate, rate=100, start_date=today, end_date=tomorrow) create_rate_per_date(rate, rate=125, start_date=tomorrow, end_date=two_days_from_now) rate_form_class = rate_admin.get_form(request, rate) rate_form = rate_form_class(instance=rate) self.assertEqual(rate_form["start_date"].value(), tomorrow) self.assertEqual(rate_form["rate"].value(), 125)
from concertapp.models import * from django.contrib import admin from django.contrib.admin.sites import AdminSite from django.contrib.auth.models import User admin_site = AdminSite() # Manage users admin_site.register(User) admin_site.register(Collection) admin_site.register(Request) admin_site.register(AudioFile) admin_site.register(AudioSegment) admin_site.register(Tag)
from django.contrib import admin from django.contrib.admin.sites import AdminSite import core import core.admin site = AdminSite("settings") # pylint: disable-msg=C0103 site.index_template = "settings/index.html" site.app_index_template = "settings/app_index.html" site.register(( core.models.Semester, core.models.Group, )) site.register(core.models.Subject, core.admin.SubjectAdmin) # site.register(core.models.Lesson, LessonAdmin)
class UserSite(AdminSite): login_form = UserAuthenticationForm def has_permission(self, request): """ Allow all users which are in 'users' group. """ return request.user.is_active \ and request.user.groups.filter(name='users').count() admin = SuperAdminSite(name='admin') staff = AdminSite(name='staff') user = UserSite(name='user') # admin admin.register(Site, SiteAdmin) admin.register(User, UserAdmin) admin.register(Group, GroupAdmin) admin.register(Author, AuthorAdmin) admin.register(BookCategory, BookCategoryAdmin) admin.register(Book, BookAdmin) admin.register(CdCategory, CdCategoryAdmin) admin.register(Cd, CdAdmin) admin.register(DvdCategory, DvdCategoryAdmin) admin.register(Dvd, DvdAdmin)
from django.contrib.admin.sites import AdminSite from libscampi.contrib.cms.renaissance import models as renaissance_models, admin as renaissance_admin from libscampi.contrib.cms.conduit import models as conduit_models, admin as conduit_admin from libscampi.contrib.cms.communism import models as communism_models, admin as communism_admin from libscampi.contrib.cms.newsengine import models as newsengine_models, admin as newsengine_admin cms_admin = AdminSite() # Admin for communism cms_admin.register(communism_models.Theme) cms_admin.register(communism_models.StyleSheet, communism_admin.GenericDOMElementAdmin) cms_admin.register(communism_models.Javascript, communism_admin.GenericDOMElementAdmin) cms_admin.register(communism_models.Realm, communism_admin.RealmAdmin) cms_admin.register(communism_models.RealmNotification, communism_admin.RealmNotificationAdmin) cms_admin.register(communism_models.Section, communism_admin.SectionAdmin) cms_admin.register(communism_models.Slice, communism_admin.SliceAdmin) cms_admin.register(communism_models.NamedBox, communism_admin.BoxAdmin) cms_admin.register(communism_models.Commune, communism_admin.CommuneAdmin) cms_admin.register(communism_models.Application, communism_admin.ApplicationAdmin) # Admin for conduit cms_admin.register(conduit_models.DynamicPicker, conduit_admin.DynamicPickerAdmin) cms_admin.register(conduit_models.StaticPicker) cms_admin.register(conduit_models.PickerTemplate, conduit_admin.PickerTemplateAdmin) # Admin for newsengine cms_admin.register(newsengine_models.Article, newsengine_admin.ArticleAdmin) cms_admin.register(newsengine_models.ArticleTranslation) cms_admin.register(newsengine_models.StoryCategory) cms_admin.register(newsengine_models.Story, newsengine_admin.StoryAdmin) cms_admin.register(newsengine_models.PublishCategory, newsengine_admin.PublishCategoryAdmin)
from django.contrib.admin.sites import AdminSite from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from pages.models import Page from pages.admin import PageAdmin from registration.models import UserProfile from registration.admin import UserProfileAdmin publisher_admin = AdminSite('pageadmin') publisher_admin.register(Page, PageAdmin) publisher_admin.register(User, UserAdmin) publisher_admin.register(UserProfile, UserProfileAdmin)
def setUp(self): self.site = AdminSite()
def __init__(self, model, admin_site, *args, **kwargs): super(PolymorphicParentModelAdmin, self).__init__(model, admin_site, *args, **kwargs) self._child_admin_site = AdminSite(name=self.admin_site.name) self._is_setup = False
# 'fields':('checkin_time','checkin_station') # }), # ) date_hierarchy = 'checkin_time' ordering = ('-checkout_time',) actions = ['check_in'] search_fields = ['rider__name','rider__penncard','bike__bike_name'] save_on_top = True ## change_form_template = 'c:/djcode/penncycle/templates/admin/app/change_form.html' # make this only work for bikes not already checked in # def check_in(self, request, queryset): # return RidesAdmin.check_in(self, request, queryset) # check_in = admin_check_in def add_view(self, request, extra_context={}): try: station = request.user.groups.exclude(name='Associate')[0].name except: email_razzi("{} tried to sign somebody in it would seem. They were told to check their /admin/auth/user status. They had groups {}".format(request.user.get_full_name(), request.user.groups.all())) return HttpResponse("You don't have any groups. Go to app.penncycle.org/admin/auth/user and make sure 'associate' and your station are checked.") extra_context['station'] = station return super(pcRidesAdmin, self).add_view(request, extra_context=extra_context) pcAdminSite = AdminSite(name='pcadmin') pcAdminSite.register(Ride, pcRidesAdmin) pcAdminSite.register(Payment, PaymentAdmin) pcAdminSite.register(Bike, BikeAdmin) pcAdminSite.register(Student, StudentAdmin) pcAdminSite.register(Comment) # pcAdminSite.register(Station)
'''Defines the three AdminSite. Created on Feb 8, 2013 @author: Cam Moore ''' from django.contrib.admin.sites import AdminSite challenge_designer_site = AdminSite(name="Challenge Designer Admin") challenge_designer_site.index_template = "admin/designer_index.html" challenge_manager_site = AdminSite(name="Challenge Manager Admin") challenge_manager_site.index_template = "admin/admin_index.html" sys_admin_site = AdminSite(name='System Administration Admin') developer_site = AdminSite(name="Developer Admin") developer_site.index_template = "admin/developer_index.html"
from django.contrib.admin.sites import AdminSite from simple_history.admin import SimpleHistoryAdmin from .models import State site = AdminSite(name="other_admin") site.register(State, SimpleHistoryAdmin)
list_display = ('desc', 'date', 'project') list_filter = ('project',) class NewsAdmin(admin.ModelAdmin): list_display = ('short', 'date', 'project') list_filter = ('project',) #admin.site.unregister(User) have to make contrib/auth/admin.py load first.. admin.site.register(GivingProject, GPAdmin) admin.site.register(Membership, MembershipAdmin) admin.site.register(NewsItem, NewsAdmin) admin.site.register(Event, EventAdmin) admin.site.register(Donor, DonorAdmin) # advanced advanced_admin = AdminSite(name='advanced') class DonorAdvanced(admin.ModelAdmin): list_display = ('__unicode__', 'membership', 'asked', 'pledged', 'gifted') list_filter = ('asked', 'membership__giving_project') search_fields = ['firstname', 'lastname'] class MembershipAdvanced(admin.ModelAdmin): list_display = ('member', 'giving_project', estimated, pledged, overdue_steps, 'last_activity', 'approved', 'leader') actions = [approve] list_filter = ('approved', 'leader', 'giving_project') class MemberAdvanced(admin.ModelAdmin): list_display = ('__unicode__', 'email') search_fields = ['first_name', 'last_name', 'email']
class UserSite(AdminSite): login_form = UserAuthenticationForm def has_permission(self, request): """ Allow all users which are in 'users' group. """ return request.user.is_active \ and request.user.groups.filter(name='users').count() admin = SuperAdminSite(name='adminpanel') staff = AdminSite(name='staffpanel') user = UserSite(name='userpanel') # admin admin.register(Site, SiteAdmin) admin.register(User, UserAdmin) admin.register(Group, GroupAdmin) admin.register(Author, AuthorAdmin) admin.register(BookCategory, BookCategoryAdmin) admin.register(Book, BookAdmin) admin.register(CdCategory, CdCategoryAdmin) admin.register(Cd, CdAdmin) admin.register(DvdCategory, DvdCategoryAdmin) admin.register(Dvd, DvdAdmin)
class ModelAdminTests(TestCase): def setUp(self): self.band = Band.objects.create( name='The Doors', bio='', sign_date=date(1965, 1, 1), ) self.site = AdminSite() def test_modeladmin_str(self): ma = ModelAdmin(Band, self.site) self.assertEqual(str(ma), 'modeladmin.ModelAdmin') # form/fields/fieldsets interaction ############################## def test_default_fields(self): ma = ModelAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'bio', 'sign_date']) self.assertEqual(list(ma.get_fields(request)), ['name', 'bio', 'sign_date']) self.assertEqual(list(ma.get_fields(request, self.band)), ['name', 'bio', 'sign_date']) self.assertIsNone(ma.get_exclude(request, self.band)) def test_default_fieldsets(self): # fieldsets_add and fieldsets_change should return a special data structure that # is used in the templates. They should generate the "right thing" whether we # have specified a custom form, the fields argument, or nothing at all. # # Here's the default case. There are no custom form_add/form_change methods, # no fields argument, and no fieldsets argument. ma = ModelAdmin(Band, self.site) self.assertEqual(ma.get_fieldsets(request), [(None, {'fields': ['name', 'bio', 'sign_date']})]) self.assertEqual(ma.get_fieldsets(request, self.band), [(None, {'fields': ['name', 'bio', 'sign_date']})]) def test_get_fieldsets(self): # get_fieldsets() is called when figuring out form fields (#18681). class BandAdmin(ModelAdmin): def get_fieldsets(self, request, obj=None): return [(None, {'fields': ['name', 'bio']})] ma = BandAdmin(Band, self.site) form = ma.get_form(None) self.assertEqual(form._meta.fields, ['name', 'bio']) class InlineBandAdmin(TabularInline): model = Concert fk_name = 'main_band' can_delete = False def get_fieldsets(self, request, obj=None): return [(None, {'fields': ['day', 'transport']})] ma = InlineBandAdmin(Band, self.site) form = ma.get_formset(None).form self.assertEqual(form._meta.fields, ['day', 'transport']) def test_lookup_allowed_allows_nonexistent_lookup(self): """ A lookup_allowed allows a parameter whose field lookup doesn't exist. (#21129). """ class BandAdmin(ModelAdmin): fields = ['name'] ma = BandAdmin(Band, self.site) self.assertTrue(ma.lookup_allowed('name__nonexistent', 'test_value')) @isolate_apps('modeladmin') def test_lookup_allowed_onetoone(self): class Department(models.Model): code = models.CharField(max_length=4, unique=True) class Employee(models.Model): department = models.ForeignKey(Department, models.CASCADE, to_field="code") class EmployeeProfile(models.Model): employee = models.OneToOneField(Employee, models.CASCADE) class EmployeeInfo(models.Model): employee = models.OneToOneField(Employee, models.CASCADE) description = models.CharField(max_length=100) class EmployeeProfileAdmin(ModelAdmin): list_filter = [ 'employee__employeeinfo__description', 'employee__department__code', ] ma = EmployeeProfileAdmin(EmployeeProfile, self.site) # Reverse OneToOneField self.assertIs(ma.lookup_allowed('employee__employeeinfo__description', 'test_value'), True) # OneToOneField and ForeignKey self.assertIs(ma.lookup_allowed('employee__department__code', 'test_value'), True) def test_field_arguments(self): # If fields is specified, fieldsets_add and fieldsets_change should # just stick the fields into a formsets structure and return it. class BandAdmin(ModelAdmin): fields = ['name'] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_fields(request)), ['name']) self.assertEqual(list(ma.get_fields(request, self.band)), ['name']) self.assertEqual(ma.get_fieldsets(request), [(None, {'fields': ['name']})]) self.assertEqual(ma.get_fieldsets(request, self.band), [(None, {'fields': ['name']})]) def test_field_arguments_restricted_on_form(self): # If fields or fieldsets is specified, it should exclude fields on the # Form class to the fields specified. This may cause errors to be # raised in the db layer if required model fields aren't in fields/ # fieldsets, but that's preferable to ghost errors where a field in the # Form class isn't being displayed because it's not in fields/fieldsets. # Using `fields`. class BandAdmin(ModelAdmin): fields = ['name'] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name']) self.assertEqual(list(ma.get_form(request, self.band).base_fields), ['name']) # Using `fieldsets`. class BandAdmin(ModelAdmin): fieldsets = [(None, {'fields': ['name']})] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name']) self.assertEqual(list(ma.get_form(request, self.band).base_fields), ['name']) # Using `exclude`. class BandAdmin(ModelAdmin): exclude = ['bio'] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date']) # You can also pass a tuple to `exclude`. class BandAdmin(ModelAdmin): exclude = ('bio',) ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date']) # Using `fields` and `exclude`. class BandAdmin(ModelAdmin): fields = ['name', 'bio'] exclude = ['bio'] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name']) def test_custom_form_meta_exclude_with_readonly(self): """ The custom ModelForm's `Meta.exclude` is respected when used in conjunction with `ModelAdmin.readonly_fields` and when no `ModelAdmin.exclude` is defined (#14496). """ # With ModelAdmin class AdminBandForm(forms.ModelForm): class Meta: model = Band exclude = ['bio'] class BandAdmin(ModelAdmin): readonly_fields = ['name'] form = AdminBandForm ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['sign_date']) # With InlineModelAdmin class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ['day'] class ConcertInline(TabularInline): readonly_fields = ['transport'] form = AdminConcertForm fk_name = 'main_band' model = Concert class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ['main_band', 'opening_band', 'id', 'DELETE']) def test_custom_formfield_override_readonly(self): class AdminBandForm(forms.ModelForm): name = forms.CharField() class Meta: exclude = () model = Band class BandAdmin(ModelAdmin): form = AdminBandForm readonly_fields = ['name'] ma = BandAdmin(Band, self.site) # `name` shouldn't appear in base_fields because it's part of # readonly_fields. self.assertEqual( list(ma.get_form(request).base_fields), ['bio', 'sign_date'] ) # But it should appear in get_fields()/fieldsets() so it can be # displayed as read-only. self.assertEqual( list(ma.get_fields(request)), ['bio', 'sign_date', 'name'] ) self.assertEqual( list(ma.get_fieldsets(request)), [(None, {'fields': ['bio', 'sign_date', 'name']})] ) def test_custom_form_meta_exclude(self): """ The custom ModelForm's `Meta.exclude` is overridden if `ModelAdmin.exclude` or `InlineModelAdmin.exclude` are defined (#14496). """ # With ModelAdmin class AdminBandForm(forms.ModelForm): class Meta: model = Band exclude = ['bio'] class BandAdmin(ModelAdmin): exclude = ['name'] form = AdminBandForm ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['bio', 'sign_date']) # With InlineModelAdmin class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ['day'] class ConcertInline(TabularInline): exclude = ['transport'] form = AdminConcertForm fk_name = 'main_band' model = Concert class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ['main_band', 'opening_band', 'day', 'id', 'DELETE'] ) def test_overriding_get_exclude(self): class BandAdmin(ModelAdmin): def get_exclude(self, request, obj=None): return ['name'] self.assertEqual( list(BandAdmin(Band, self.site).get_form(request).base_fields), ['bio', 'sign_date'] ) def test_get_exclude_overrides_exclude(self): class BandAdmin(ModelAdmin): exclude = ['bio'] def get_exclude(self, request, obj=None): return ['name'] self.assertEqual( list(BandAdmin(Band, self.site).get_form(request).base_fields), ['bio', 'sign_date'] ) def test_get_exclude_takes_obj(self): class BandAdmin(ModelAdmin): def get_exclude(self, request, obj=None): if obj: return ['sign_date'] return ['name'] self.assertEqual( list(BandAdmin(Band, self.site).get_form(request, self.band).base_fields), ['name', 'bio'] ) def test_custom_form_validation(self): # If a form is specified, it should use it allowing custom validation # to work properly. This won't break any of the admin widgets or media. class AdminBandForm(forms.ModelForm): delete = forms.BooleanField() class BandAdmin(ModelAdmin): form = AdminBandForm ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'bio', 'sign_date', 'delete']) self.assertEqual(type(ma.get_form(request).base_fields['sign_date'].widget), AdminDateWidget) def test_form_exclude_kwarg_override(self): """ The `exclude` kwarg passed to `ModelAdmin.get_form()` overrides all other declarations (#8999). """ class AdminBandForm(forms.ModelForm): class Meta: model = Band exclude = ['name'] class BandAdmin(ModelAdmin): exclude = ['sign_date'] form = AdminBandForm def get_form(self, request, obj=None, **kwargs): kwargs['exclude'] = ['bio'] return super().get_form(request, obj, **kwargs) ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date']) def test_formset_exclude_kwarg_override(self): """ The `exclude` kwarg passed to `InlineModelAdmin.get_formset()` overrides all other declarations (#8999). """ class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ['day'] class ConcertInline(TabularInline): exclude = ['transport'] form = AdminConcertForm fk_name = 'main_band' model = Concert def get_formset(self, request, obj=None, **kwargs): kwargs['exclude'] = ['opening_band'] return super().get_formset(request, obj, **kwargs) class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ['main_band', 'day', 'transport', 'id', 'DELETE'] ) def test_formset_overriding_get_exclude_with_form_fields(self): class AdminConcertForm(forms.ModelForm): class Meta: model = Concert fields = ['main_band', 'opening_band', 'day', 'transport'] class ConcertInline(TabularInline): form = AdminConcertForm fk_name = 'main_band' model = Concert def get_exclude(self, request, obj=None): return ['opening_band'] class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ['main_band', 'day', 'transport', 'id', 'DELETE'] ) def test_formset_overriding_get_exclude_with_form_exclude(self): class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ['day'] class ConcertInline(TabularInline): form = AdminConcertForm fk_name = 'main_band' model = Concert def get_exclude(self, request, obj=None): return ['opening_band'] class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ['main_band', 'day', 'transport', 'id', 'DELETE'] ) def test_queryset_override(self): # If the queryset of a ModelChoiceField in a custom form is overridden, # RelatedFieldWidgetWrapper doesn't mess that up. band2 = Band.objects.create(name='The Beatles', bio='', sign_date=date(1962, 1, 1)) ma = ModelAdmin(Concert, self.site) form = ma.get_form(request)() self.assertHTMLEqual( str(form["main_band"]), '<div class="related-widget-wrapper">' '<select name="main_band" id="id_main_band" required>' '<option value="" selected>---------</option>' '<option value="%d">The Beatles</option>' '<option value="%d">The Doors</option>' '</select></div>' % (band2.id, self.band.id) ) class AdminConcertForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["main_band"].queryset = Band.objects.filter(name='The Doors') class ConcertAdminWithForm(ModelAdmin): form = AdminConcertForm ma = ConcertAdminWithForm(Concert, self.site) form = ma.get_form(request)() self.assertHTMLEqual( str(form["main_band"]), '<div class="related-widget-wrapper">' '<select name="main_band" id="id_main_band" required>' '<option value="" selected>---------</option>' '<option value="%d">The Doors</option>' '</select></div>' % self.band.id ) def test_regression_for_ticket_15820(self): """ `obj` is passed from `InlineModelAdmin.get_fieldsets()` to `InlineModelAdmin.get_formset()`. """ class CustomConcertForm(forms.ModelForm): class Meta: model = Concert fields = ['day'] class ConcertInline(TabularInline): model = Concert fk_name = 'main_band' def get_formset(self, request, obj=None, **kwargs): if obj: kwargs['form'] = CustomConcertForm return super().get_formset(request, obj, **kwargs) class BandAdmin(ModelAdmin): inlines = [ConcertInline] Concert.objects.create(main_band=self.band, opening_band=self.band, day=1) ma = BandAdmin(Band, self.site) inline_instances = ma.get_inline_instances(request) fieldsets = list(inline_instances[0].get_fieldsets(request)) self.assertEqual(fieldsets[0][1]['fields'], ['main_band', 'opening_band', 'day', 'transport']) fieldsets = list(inline_instances[0].get_fieldsets(request, inline_instances[0].model)) self.assertEqual(fieldsets[0][1]['fields'], ['day']) # radio_fields behavior ########################################### def test_default_foreign_key_widget(self): # First, without any radio_fields specified, the widgets for ForeignKey # and fields with choices specified ought to be a basic Select widget. # ForeignKey widgets in the admin are wrapped with RelatedFieldWidgetWrapper so # they need to be handled properly when type checking. For Select fields, all of # the choices lists have a first entry of dashes. cma = ModelAdmin(Concert, self.site) cmafa = cma.get_form(request) self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget), Select) self.assertEqual( list(cmafa.base_fields['main_band'].widget.choices), [('', '---------'), (self.band.id, 'The Doors')]) self.assertEqual(type(cmafa.base_fields['opening_band'].widget.widget), Select) self.assertEqual( list(cmafa.base_fields['opening_band'].widget.choices), [('', '---------'), (self.band.id, 'The Doors')] ) self.assertEqual(type(cmafa.base_fields['day'].widget), Select) self.assertEqual( list(cmafa.base_fields['day'].widget.choices), [('', '---------'), (1, 'Fri'), (2, 'Sat')] ) self.assertEqual(type(cmafa.base_fields['transport'].widget), Select) self.assertEqual( list(cmafa.base_fields['transport'].widget.choices), [('', '---------'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')]) def test_foreign_key_as_radio_field(self): # Now specify all the fields as radio_fields. Widgets should now be # RadioSelect, and the choices list should have a first entry of 'None' if # blank=True for the model field. Finally, the widget should have the # 'radiolist' attr, and 'inline' as well if the field is specified HORIZONTAL. class ConcertAdmin(ModelAdmin): radio_fields = { 'main_band': HORIZONTAL, 'opening_band': VERTICAL, 'day': VERTICAL, 'transport': HORIZONTAL, } cma = ConcertAdmin(Concert, self.site) cmafa = cma.get_form(request) self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget), AdminRadioSelect) self.assertEqual(cmafa.base_fields['main_band'].widget.attrs, {'class': 'radiolist inline'}) self.assertEqual( list(cmafa.base_fields['main_band'].widget.choices), [(self.band.id, 'The Doors')] ) self.assertEqual(type(cmafa.base_fields['opening_band'].widget.widget), AdminRadioSelect) self.assertEqual(cmafa.base_fields['opening_band'].widget.attrs, {'class': 'radiolist'}) self.assertEqual( list(cmafa.base_fields['opening_band'].widget.choices), [('', 'None'), (self.band.id, 'The Doors')] ) self.assertEqual(type(cmafa.base_fields['day'].widget), AdminRadioSelect) self.assertEqual(cmafa.base_fields['day'].widget.attrs, {'class': 'radiolist'}) self.assertEqual(list(cmafa.base_fields['day'].widget.choices), [(1, 'Fri'), (2, 'Sat')]) self.assertEqual(type(cmafa.base_fields['transport'].widget), AdminRadioSelect) self.assertEqual(cmafa.base_fields['transport'].widget.attrs, {'class': 'radiolist inline'}) self.assertEqual( list(cmafa.base_fields['transport'].widget.choices), [('', 'None'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')] ) class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ('transport',) class ConcertAdmin(ModelAdmin): form = AdminConcertForm ma = ConcertAdmin(Concert, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['main_band', 'opening_band', 'day']) class AdminConcertForm(forms.ModelForm): extra = forms.CharField() class Meta: model = Concert fields = ['extra', 'transport'] class ConcertAdmin(ModelAdmin): form = AdminConcertForm ma = ConcertAdmin(Concert, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['extra', 'transport']) class ConcertInline(TabularInline): form = AdminConcertForm model = Concert fk_name = 'main_band' can_delete = True class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ['extra', 'transport', 'id', 'DELETE', 'main_band'] ) def test_log_actions(self): ma = ModelAdmin(Band, self.site) mock_request = MockRequest() mock_request.user = User.objects.create(username='******') content_type = get_content_type_for_model(self.band) tests = ( (ma.log_addition, ADDITION, {'added': {}}), (ma.log_change, CHANGE, {'changed': {'fields': ['name', 'bio']}}), (ma.log_deletion, DELETION, str(self.band)), ) for method, flag, message in tests: with self.subTest(name=method.__name__): created = method(mock_request, self.band, message) fetched = LogEntry.objects.filter(action_flag=flag).latest('id') self.assertEqual(created, fetched) self.assertEqual(fetched.action_flag, flag) self.assertEqual(fetched.content_type, content_type) self.assertEqual(fetched.object_id, str(self.band.pk)) self.assertEqual(fetched.user, mock_request.user) if flag == DELETION: self.assertEqual(fetched.change_message, '') self.assertEqual(fetched.object_repr, message) else: self.assertEqual(fetched.change_message, str(message)) self.assertEqual(fetched.object_repr, str(self.band)) def test_get_autocomplete_fields(self): class NameAdmin(ModelAdmin): search_fields = ['name'] class SongAdmin(ModelAdmin): autocomplete_fields = ['featuring'] fields = ['featuring', 'band'] class OtherSongAdmin(SongAdmin): def get_autocomplete_fields(self, request): return ['band'] self.site.register(Band, NameAdmin) try: # Uses autocomplete_fields if not overridden. model_admin = SongAdmin(Song, self.site) form = model_admin.get_form(request)() self.assertIsInstance(form.fields['featuring'].widget.widget, AutocompleteSelectMultiple) # Uses overridden get_autocomplete_fields model_admin = OtherSongAdmin(Song, self.site) form = model_admin.get_form(request)() self.assertIsInstance(form.fields['band'].widget.widget, AutocompleteSelect) finally: self.site.unregister(Band) def test_get_deleted_objects(self): mock_request = MockRequest() mock_request.user = User.objects.create_superuser(username='******', email='*****@*****.**', password='******') self.site.register(Band, ModelAdmin) ma = self.site._registry[Band] deletable_objects, model_count, perms_needed, protected = ma.get_deleted_objects([self.band], request) self.assertEqual(deletable_objects, ['Band: The Doors']) self.assertEqual(model_count, {'bands': 1}) self.assertEqual(perms_needed, set()) self.assertEqual(protected, []) def test_get_deleted_objects_with_custom_has_delete_permission(self): """ ModelAdmin.get_deleted_objects() uses ModelAdmin.has_delete_permission() for permissions checking. """ mock_request = MockRequest() mock_request.user = User.objects.create_superuser(username='******', email='*****@*****.**', password='******') class TestModelAdmin(ModelAdmin): def has_delete_permission(self, request, obj=None): return False self.site.register(Band, TestModelAdmin) ma = self.site._registry[Band] deletable_objects, model_count, perms_needed, protected = ma.get_deleted_objects([self.band], request) self.assertEqual(deletable_objects, ['Band: The Doors']) self.assertEqual(model_count, {'bands': 1}) self.assertEqual(perms_needed, {'band'}) self.assertEqual(protected, [])
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib import admin from .models import MyModel from django.contrib.admin.sites import AdminSite, site myadminsite = AdminSite() class MyModelAdmin(admin.ModelAdmin): model = MyModel myadminsite.register(MyModel, MyModelAdmin)
from django.contrib.admin.sites import AdminSite from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from pages.models import Page from pages.admin import PageAdmin publisher_admin = AdminSite('pageadmin') publisher_admin.register(Page, PageAdmin) publisher_admin.register(User, UserAdmin)
class PolymorphicParentModelAdmin(admin.ModelAdmin): """ A admin interface that can displays different change/delete pages, depending on the polymorphic model. To use this class, two variables need to be defined: * :attr:`base_model` should * :attr:`child_models` should be a list of (Model, Admin) tuples Alternatively, the following methods can be implemented: * :func:`get_child_models` should return a list of (Model, ModelAdmin) tuples * optionally, :func:`get_child_type_choices` can be overwritten to refine the choices for the add dialog. This class needs to be inherited by the model admin base class that is registered in the site. The derived models should *not* register the ModelAdmin, but instead it should be returned by :func:`get_child_models`. """ #: The base model that the class uses base_model = None #: The child models that should be displayed child_models = None #: Whether the list should be polymorphic too, leave to ``False`` to optimize polymorphic_list = False add_type_template = None add_type_form = PolymorphicModelChoiceForm #: The regular expression to filter the primary key in the URL. #: This accepts only numbers as defensive measure against catch-all URLs. #: If your primary key consists of string values, update this regular expression. pk_regex = '(\d+)' def __init__(self, model, admin_site, *args, **kwargs): super(PolymorphicParentModelAdmin, self).__init__(model, admin_site, *args, **kwargs) self._child_admin_site = AdminSite(name=self.admin_site.name) self._is_setup = False def _lazy_setup(self): if self._is_setup: return # By not having this in __init__() there is less stress on import dependencies as well, # considering an advanced use cases where a plugin system scans for the child models. child_models = self.get_child_models() for Model, Admin in child_models: self.register_child(Model, Admin) self._child_models = dict(child_models) # This is needed to deal with the improved ForeignKeyRawIdWidget in Django 1.4 and perhaps other widgets too. # The ForeignKeyRawIdWidget checks whether the referenced model is registered in the admin, otherwise it displays itself as a textfield. # As simple solution, just make sure all parent admin models are also know in the child admin site. # This should be done after all parent models are registered off course. complete_registry = self.admin_site._registry.copy() complete_registry.update(self._child_admin_site._registry) self._child_admin_site._registry = complete_registry self._is_setup = True def register_child(self, model, model_admin): """ Register a model with admin to display. """ # After the get_urls() is called, the URLs of the child model can't be exposed anymore to the Django URLconf, # which also means that a "Save and continue editing" button won't work. if self._is_setup: raise RegistrationClosed("The admin model can't be registered anymore at this point.") if not issubclass(model, self.base_model): raise TypeError("{0} should be a subclass of {1}".format(model.__name__, self.base_model.__name__)) if not issubclass(model_admin, admin.ModelAdmin): raise TypeError("{0} should be a subclass of {1}".format(model_admin.__name__, admin.ModelAdmin.__name__)) self._child_admin_site.register(model, model_admin) def get_child_models(self): """ Return the derived model classes which this admin should handle. This should return a list of tuples, exactly like :attr:`child_models` is. The model classes can be retrieved as ``base_model.__subclasses__()``, a setting in a config file, or a query of a plugin registration system at your option """ if self.child_models is None: raise NotImplementedError("Implement get_child_models() or child_models") return self.child_models def get_child_type_choices(self): """ Return a list of polymorphic types which can be added. """ choices = [] for model, _ in self.get_child_models(): ct = ContentType.objects.get_for_model(model, for_concrete_model=False) choices.append((ct.id, model._meta.verbose_name)) return choices def _get_real_admin(self, object_id): obj = self.model.objects.non_polymorphic().values('polymorphic_ctype').get(pk=object_id) return self._get_real_admin_by_ct(obj['polymorphic_ctype']) def _get_real_admin_by_ct(self, ct_id): try: ct = ContentType.objects.get_for_id(ct_id) except ContentType.DoesNotExist as e: raise Http404(e) # Handle invalid GET parameters model_class = ct.model_class() if not model_class: raise Http404("No model found for '{0}.{1}'.".format(*ct.natural_key())) # Handle model deletion return self._get_real_admin_by_model(model_class) def _get_real_admin_by_model(self, model_class): # In case of a ?ct_id=### parameter, the view is already checked for permissions. # Hence, make sure this is a derived object, or risk exposing other admin interfaces. if model_class not in self._child_models: raise PermissionDenied("Invalid model '{0}', it must be registered as child model.".format(model_class)) try: # HACK: the only way to get the instance of an model admin, # is to read the registry of the AdminSite. return self._child_admin_site._registry[model_class] except KeyError: raise ChildAdminNotRegistered("No child admin site was registered for a '{0}' model.".format(model_class)) def queryset(self, request): # optimize the list display. qs = super(PolymorphicParentModelAdmin, self).queryset(request) if not self.polymorphic_list: qs = qs.non_polymorphic() return qs def add_view(self, request, form_url='', extra_context=None): """Redirect the add view to the real admin.""" ct_id = int(request.GET.get('ct_id', 0)) if not ct_id: # Display choices return self.add_type_view(request) else: real_admin = self._get_real_admin_by_ct(ct_id) return real_admin.add_view(request, form_url, extra_context) def change_view(self, request, object_id, *args, **kwargs): """Redirect the change view to the real admin.""" # between Django 1.3 and 1.4 this method signature differs. Hence the *args, **kwargs real_admin = self._get_real_admin(object_id) return real_admin.change_view(request, object_id, *args, **kwargs) def delete_view(self, request, object_id, extra_context=None): """Redirect the delete view to the real admin.""" real_admin = self._get_real_admin(object_id) return real_admin.delete_view(request, object_id, extra_context) def get_urls(self): """ Expose the custom URLs for the subclasses and the URL resolver. """ urls = super(PolymorphicParentModelAdmin, self).get_urls() info = self.model._meta.app_label, self.model._meta.module_name # Patch the change URL so it's not a big catch-all; allowing all custom URLs to be added to the end. # The url needs to be recreated, patching url.regex is not an option Django 1.4's LocaleRegexProvider changed it. new_change_url = url(r'^{0}/$'.format(self.pk_regex), self.admin_site.admin_view(self.change_view), name='{0}_{1}_change'.format(*info)) for i, oldurl in enumerate(urls): if oldurl.name == new_change_url.name: urls[i] = new_change_url # Define the catch-all for custom views custom_urls = patterns('', url(r'^(?P<path>.+)$', self.admin_site.admin_view(self.subclass_view)) ) # At this point. all admin code needs to be known. self._lazy_setup() # Add reverse names for all polymorphic models, so the delete button and "save and add" just work. # These definitions are masked by the definition above, since it needs special handling (and a ct_id parameter). dummy_urls = [] for model, _ in self.get_child_models(): admin = self._get_real_admin_by_model(model) dummy_urls += admin.get_urls() return urls + custom_urls + dummy_urls def subclass_view(self, request, path): """ Forward any request to a custom view of the real admin. """ ct_id = int(request.GET.get('ct_id', 0)) if not ct_id: # See if the path started with an ID. try: pos = path.find('/') object_id = long(path[0:pos]) except ValueError: raise Http404("No ct_id parameter, unable to find admin subclass for path '{0}'.".format(path)) ct_id = self.model.objects.values_list('polymorphic_ctype_id', flat=True).get(pk=object_id) real_admin = self._get_real_admin_by_ct(ct_id) resolver = RegexURLResolver('^', real_admin.urls) resolvermatch = resolver.resolve(path) # May raise Resolver404 if not resolvermatch: raise Http404("No match for path '{0}' in admin subclass.".format(path)) return resolvermatch.func(request, *resolvermatch.args, **resolvermatch.kwargs) def add_type_view(self, request, form_url=''): """ Display a choice form to select which page type to add. """ if not self.has_add_permission(request): raise PermissionDenied extra_qs = '' if request.META['QUERY_STRING']: extra_qs = '&' + request.META['QUERY_STRING'] choices = self.get_child_type_choices() if len(choices) == 1: return HttpResponseRedirect('?ct_id={0}{1}'.format(choices[0][0], extra_qs)) # Create form form = self.add_type_form( data=request.POST if request.method == 'POST' else None, initial={'ct_id': choices[0][0]} ) form.fields['ct_id'].choices = choices if form.is_valid(): return HttpResponseRedirect('?ct_id={0}{1}'.format(form.cleaned_data['ct_id'], extra_qs)) # Wrap in all admin layout fieldsets = ((None, {'fields': ('ct_id',)}),) adminForm = AdminForm(form, fieldsets, {}, model_admin=self) media = self.media + adminForm.media opts = self.model._meta context = { 'title': _('Add %s') % force_text(opts.verbose_name), 'adminform': adminForm, 'is_popup': "_popup" in request.REQUEST, 'media': mark_safe(media), 'errors': AdminErrorList(form, ()), 'app_label': opts.app_label, } return self.render_add_type_form(request, context, form_url) def render_add_type_form(self, request, context, form_url=''): """ Render the page type choice form. """ opts = self.model._meta app_label = opts.app_label context.update({ 'has_change_permission': self.has_change_permission(request), 'form_url': mark_safe(form_url), 'opts': opts, 'add': True, 'save_on_top': self.save_on_top, }) if hasattr(self.admin_site, 'root_path'): context['root_path'] = self.admin_site.root_path # Django < 1.4 context_instance = RequestContext(request, current_app=self.admin_site.name) return render_to_response(self.add_type_template or [ "admin/%s/%s/add_type_form.html" % (app_label, opts.object_name.lower()), "admin/%s/add_type_form.html" % app_label, "admin/polymorphic/add_type_form.html", # added default here "admin/add_type_form.html" ], context, context_instance=context_instance) @property def change_list_template(self): opts = self.model._meta app_label = opts.app_label # Pass the base options base_opts = self.base_model._meta base_app_label = base_opts.app_label return [ "admin/%s/%s/change_list.html" % (app_label, opts.object_name.lower()), "admin/%s/change_list.html" % app_label, # Added base class: "admin/%s/%s/change_list.html" % (base_app_label, base_opts.object_name.lower()), "admin/%s/change_list.html" % base_app_label, "admin/change_list.html" ]
from django.contrib import admin from django.contrib.admin.sites import AdminSite from django.contrib.auth.models import User from flatblocks.models import FlatBlock from courses.models import ( Course, Student, Subject, Teacher, Timeslot, UserProfile) admin_site = AdminSite() class CourseAdmin(admin.ModelAdmin): pass admin_site.register(Course, CourseAdmin) admin_site.register(User) class UserProfileAdmin(admin.ModelAdmin): pass admin_site.register(UserProfile, UserProfileAdmin) class StudentAdmin(admin.ModelAdmin): pass
from django.contrib import admin from django.forms import ModelForm from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from productions.models import * from auditions.models import * from django.contrib.admin.sites import AdminSite admin_site = AdminSite() # Allow administration of admin users admin_site.register(User) # Allow administration of productions admin_site.register(ProductionType) class ProductionAdmin(admin.ModelAdmin): list_display = ('name', 'default_production') admin_site.register(Production, ProductionAdmin) # The form which is used for each audition when editing an actor. class AuditionInlineForm(ModelForm): model = Audition def __init__(self, *args, **kwargs): super(AuditionInlineForm, self).__init__(*args, **kwargs)
from django.conf.urls import include, patterns, url from django.contrib.admin.sites import AdminSite from multilingual.admin import MultilingualModelAdmin from .models import Multiling SITE = AdminSite() SITE.register(Multiling, MultilingualModelAdmin) urlpatterns = patterns('', url(r'^admin/', include(SITE.urls)), )