Python django.contrib.admin.site() Examples

The following are 30 code examples of django.contrib.admin.site(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.admin , or try the search function .
Example #1
Source File: test_checks.py    From django-hijack-admin with MIT License 6 votes vote down vote up
def test_check_custom_user_model_default_admin(self):
            # Django doesn't re-register admins when using `override_settings`,
            # so we have to do it manually in this test case.
            admin.site.register(get_user_model(), UserAdmin)

            warnings = checks.check_custom_user_model(HijackAdminConfig)
            expected_warnings = [
                Warning(
                    'django-hijack-admin does not work out the box with a custom user model.',
                    hint='Please mix HijackUserAdminMixin into your custom UserAdmin.',
                    obj=settings.AUTH_USER_MODEL,
                    id='hijack_admin.W001',
                )
            ]
            self.assertEqual(warnings, expected_warnings)

            admin.site.unregister(get_user_model()) 
Example #2
Source File: utils.py    From django-admin-tools with MIT License 6 votes vote down vote up
def get_admin_site(context=None, request=None):
    dashboard_cls = getattr(
        settings,
        'ADMIN_TOOLS_INDEX_DASHBOARD',
        'admin_tools.dashboard.dashboards.DefaultIndexDashboard'
    )

    if isinstance(dashboard_cls, dict):
        if context:
            request = context.get('request')
        curr_url = request.path
        for key in dashboard_cls:
            mod, inst = key.rsplit('.', 1)
            mod = import_module(mod)
            admin_site = getattr(mod, inst)
            admin_url = reverse('%s:index' % admin_site.name)
            if curr_url.startswith(admin_url):
                return admin_site
    else:
        return admin.site
    raise ValueError('Admin site matching "%s" not found' % dashboard_cls) 
Example #3
Source File: test_admin_filter.py    From django-enum-choices with MIT License 6 votes vote down vote up
def test_list_filter_queryset_filters_objects_correctly(self):
        StringEnumeratedModel.objects.create(enumeration=CharTestEnum.FIRST)
        StringEnumeratedModel.objects.create(enumeration=CharTestEnum.SECOND)
        StringEnumeratedModel.objects.create(enumeration=CharTestEnum.THIRD)

        modeladmin = StringEnumAdmin(
            StringEnumeratedModel,
            admin.site
        )

        for enumeration in CharTestEnum:
            request = self.request_factory.get('/', {'enumeration__exact': enumeration.value})
            request.user = self.user

            changelist = self.get_changelist_instance(request, StringEnumeratedModel, modeladmin)

            self.assertEqual(changelist.queryset.count(), 1) 
Example #4
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_formfield_overrides_widget_instances(self):
        """
        Widget instances in formfield_overrides are not shared between
        different fields. (#19423)
        """
        class BandAdmin(admin.ModelAdmin):
            formfield_overrides = {
                CharField: {'widget': forms.TextInput(attrs={'size': '10'})}
            }
        ma = BandAdmin(Band, admin.site)
        f1 = ma.formfield_for_dbfield(Band._meta.get_field('name'), request=None)
        f2 = ma.formfield_for_dbfield(Band._meta.get_field('style'), request=None)
        self.assertNotEqual(f1.widget, f2.widget)
        self.assertEqual(f1.widget.attrs['maxlength'], '100')
        self.assertEqual(f2.widget.attrs['maxlength'], '20')
        self.assertEqual(f2.widget.attrs['size'], '10') 
Example #5
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_label_and_url_for_value_invalid_uuid(self):
        field = Bee._meta.get_field('honeycomb')
        self.assertIsInstance(field.target_field, UUIDField)
        widget = widgets.ForeignKeyRawIdWidget(field.remote_field, admin.site)
        self.assertEqual(widget.label_and_url_for_value('invalid-uuid'), ('', '')) 
Example #6
Source File: adminlte_menu.py    From django-adminlte-ui with MIT License 6 votes vote down vote up
def get_admin_site(current_app):
    """
    Method tries to get actual admin.site class, if any custom admin sites
    were used. Couldn't find any other references to actual class other than
    in func_closer dict in index() func returned by resolver.
    """
    try:
        resolver_match = resolve(reverse('%s:index' % current_app))
        # Django 1.9 exposes AdminSite instance directly on view function
        if hasattr(resolver_match.func, 'admin_site'):
            return resolver_match.func.admin_site

        for func_closure in resolver_match.func.__closure__:
            if isinstance(func_closure.cell_contents, AdminSite):
                return func_closure.cell_contents
    except:
        pass
    from django.contrib import admin
    return admin.site 
Example #7
Source File: suit_menu.py    From django-ra-erp with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_admin_site(current_app):
    """
    Method tries to get actual admin.site class, if any custom admin sites
    were used. Couldn't find any other references to actual class other than
    in func_closer dict in index() func returned by resolver.
    """
    try:
        resolver_match = resolve(reverse('%s:index' % current_app))
        # Django 1.9 exposes AdminSite instance directly on view function
        if hasattr(resolver_match.func, 'admin_site'):
            return resolver_match.func.admin_site

        for func_closure in resolver_match.func.__closure__:
            if isinstance(func_closure.cell_contents, AdminSite):
                return func_closure.cell_contents
    except:
        pass
    return admin.site 
Example #8
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
def test_datefilter_filtered_with_one_params(self):
        self.request_factory = RequestFactory()
        modeladmin = RangeModelDTTimeAdmin(RangeModelDT, site)

        request = self.request_factory.get('/', {'created_at__range__gte_0': self.today,
                                                 'created_at__range__gte_1': self.min_time})
        request.user = self.user

        changelist = self.get_changelist(request, RangeModelDT, modeladmin)

        queryset = changelist.get_queryset(request)

        self.assertEqual(list(queryset), [self.django_book])
        filterspec = changelist.get_filters(request)[0][0]
        self.assertEqual(force_str(filterspec.title), 'created at')

        choice = select_by(filterspec.choices(changelist))
        self.assertEqual(choice['query_string'], '?')
        self.assertEqual(choice['system_name'], 'created-at') 
Example #9
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
def test_datetimfilter_with_default(self):
        self.request_factory = RequestFactory()
        modeladmin = RangeModelDTTimeAdmin(RangeModelDT, site)
        modeladmin.get_rangefilter_created_at_default = lambda r: [self.today, self.tomorrow]

        request = self.request_factory.get('/')
        request.user = self.user

        changelist = self.get_changelist(request, RangeModelDT, modeladmin)

        queryset = changelist.get_queryset(request)

        self.assertEqual(list(queryset), [self.djangonaut_book, self.django_book])
        filterspec = changelist.get_filters(request)[0][0]
        self.assertEqual(force_str(filterspec.title), 'created at')
        self.assertEqual(filterspec.default_gte, self.today)
        self.assertEqual(filterspec.default_lte, self.tomorrow) 
Example #10
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
def test_datetimfilter_filtered(self):
        self.request_factory = RequestFactory()
        modeladmin = RangeModelDTTimeAdmin(RangeModelDT, site)

        request = self.request_factory.get('/', {'created_at__range__gte_0': self.today,
                                                 'created_at__range__gte_1': self.min_time,
                                                 'created_at__range__lte_0': self.tomorrow,
                                                 'created_at__range__lte_1': self.max_time})
        request.user = self.user

        changelist = self.get_changelist(request, RangeModelDT, modeladmin)

        queryset = changelist.get_queryset(request)

        self.assertEqual(list(queryset), [self.django_book])
        filterspec = changelist.get_filters(request)[0][0]
        self.assertEqual(force_str(filterspec.title), 'created at')

        choice = select_by(filterspec.choices(changelist))
        self.assertEqual(choice['query_string'], '?')
        self.assertEqual(choice['system_name'], 'created-at') 
Example #11
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
def test_datefilter_filtered_datefield(self):
        self.request_factory = RequestFactory()
        modeladmin = RangeModelDAdmin(RangeModelD, site)

        request = self.request_factory.get('/', {'created_at__range__gte': self.today,
                                                 'created_at__range__lte': self.tomorrow})
        request.user = self.user

        changelist = self.get_changelist(request, RangeModelD, modeladmin)

        queryset = changelist.get_queryset(request)

        self.assertEqual(list(queryset), [self.django_book_date])
        filterspec = changelist.get_filters(request)[0][0]
        self.assertEqual(force_str(filterspec.title), 'created at')

        choice = select_by(filterspec.choices(changelist))
        self.assertEqual(choice['query_string'], '?')
        self.assertEqual(choice['system_name'], 'created-at') 
Example #12
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
def test_datefilter_filtered_with_one_params(self):
        self.request_factory = RequestFactory()
        modeladmin = RangeModelDTAdmin(RangeModelDT, site)

        request = self.request_factory.get('/', {'created_at__range__gte': self.today})
        request.user = self.user

        changelist = self.get_changelist(request, RangeModelDT, modeladmin)

        queryset = changelist.get_queryset(request)

        self.assertEqual(list(queryset), [self.django_book])
        filterspec = changelist.get_filters(request)[0][0]
        self.assertEqual(force_str(filterspec.title), 'created at')

        choice = select_by(filterspec.choices(changelist))
        self.assertEqual(choice['query_string'], '?')
        self.assertEqual(choice['system_name'], 'created-at') 
Example #13
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
def test_datefilter_with_default(self):
        self.request_factory = RequestFactory()
        modeladmin = RangeModelDTAdmin(RangeModelDT, site)
        modeladmin.get_rangefilter_created_at_default = lambda r: [self.today, self.tomorrow]

        request = self.request_factory.get('/')
        request.user = self.user

        changelist = self.get_changelist(request, RangeModelDT, modeladmin)

        queryset = changelist.get_queryset(request)

        self.assertEqual(list(queryset), [self.djangonaut_book, self.django_book])
        filterspec = changelist.get_filters(request)[0][0]
        self.assertEqual(force_str(filterspec.title), 'created at')
        self.assertEqual(filterspec.default_gte, self.today)
        self.assertEqual(filterspec.default_lte, self.tomorrow) 
Example #14
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
def test_datefilter_filtered(self):
        self.request_factory = RequestFactory()
        modeladmin = RangeModelDTAdmin(RangeModelDT, site)

        request = self.request_factory.get('/', {'created_at__range__gte': self.today,
                                                 'created_at__range__lte': self.tomorrow})
        request.user = self.user

        changelist = self.get_changelist(request, RangeModelDT, modeladmin)

        queryset = changelist.get_queryset(request)

        self.assertEqual(list(queryset), [self.django_book])
        filterspec = changelist.get_filters(request)[0][0]
        self.assertEqual(force_str(filterspec.title), 'created at')

        choice = select_by(filterspec.choices(changelist))
        self.assertEqual(choice['query_string'], '?')
        self.assertEqual(choice['system_name'], 'created-at') 
Example #15
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_m2m_related_model_not_in_admin(self):
        # M2M relationship with model not registered with admin site. Raw ID
        # widget should have no magnifying glass link. See #16542
        consultor1 = Advisor.objects.create(name='Rockstar Techie')

        c1 = Company.objects.create(name='Doodle')
        c2 = Company.objects.create(name='Pear')
        consultor1.companies.add(c1, c2)
        rel = Advisor._meta.get_field('companies').remote_field

        w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site)
        self.assertHTMLEqual(
            w.render('company_widget1', [c1.pk, c2.pk], attrs={}),
            '<input type="text" name="company_widget1" value="%(c1pk)s,%(c2pk)s">' % {'c1pk': c1.pk, 'c2pk': c2.pk}
        )

        self.assertHTMLEqual(
            w.render('company_widget2', [c1.pk]),
            '<input type="text" name="company_widget2" value="%(c1pk)s">' % {'c1pk': c1.pk}
        ) 
Example #16
Source File: suit_menu.py    From DCRM with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_admin_site(current_app):
    """
    Method tries to get actual admin.site class, if any custom admin sites
    were used. Couldn't find any other references to actual class other than
    in func_closer dict in index() func returned by resolver.
    """
    try:
        resolver_match = resolve(reverse('%s:index' % current_app))
        # Django 1.9 exposes AdminSite instance directly on view function
        if hasattr(resolver_match.func, 'admin_site'):
            return resolver_match.func.admin_site

        for func_closure in resolver_match.func.__closure__:
            if isinstance(func_closure.cell_contents, AdminSite):
                return func_closure.cell_contents
    except:
        pass
    from django.contrib import admin
    return admin.site 
Example #17
Source File: test_all.py    From DCRM with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_queryset(self):
        # Should return preferences without sites.
        # Shouldn't fail on duplicates.
        self.failIf(MyPreferences.singleton.get().sites.all(), "Without \
                SITE_ID should not have any preferences with sites.")

        # Should return preferences for current site.
        # Shouldn't fail on duplicates.
        settings.SITE_ID = 1
        current_site = Site.objects.get_current()
        obj = MyPreferences.singleton.get()
        self.failUnlessEqual(current_site, obj.sites.get(), "With SITE_ID \
                should have preferences for current site.")

        # Should return preferences for current site.
        # Shouldn't fail on duplicates.
        settings.SITE_ID = 2
        second_site, created = Site.objects.get_or_create(id=2)
        obj = MyPreferences.singleton.get()
        self.failUnlessEqual(second_site, obj.sites.get(), "With SITE_ID \
                should have preferences for current site.") 
Example #18
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_result_list_set_empty_value_display_on_admin_site(self):
        """
        Empty value display can be set on AdminSite.
        """
        new_child = Child.objects.create(name='name', parent=None)
        request = self.factory.get('/child/')
        request.user = self.superuser
        # Set a new empty display value on AdminSite.
        admin.site.empty_value_display = '???'
        m = ChildAdmin(Child, admin.site)
        cl = m.get_changelist_instance(request)
        cl.formset = None
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl, 'opts': Child._meta})
        table_output = template.render(context)
        link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
        row_html = build_tbody_html(new_child.id, link, '<td class="field-parent nowrap">???</td>')
        self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output) 
Example #19
Source File: test_all.py    From DCRM with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_changelist_view(self):
        request = RequestFactory().get('/')
        request.user = User.objects.create(username='name', password='pass', is_superuser=True)
        admin_obj = PreferencesAdmin(MyPreferences, admin.site)

        # With only one preferences object redirect to its change view.
        response = admin_obj.changelist_view(request)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, '/admin/tests/mypreferences/1/change/')

        # With multiple preferences display listing view.
        MyPreferences.objects.create()
        response = admin_obj.changelist_view(request)
        response.render()
        self.failUnless('changelist-form' in response.content, 'Should \
display listing if multiple preferences objects are available.') 
Example #20
Source File: apps.py    From django-admin-view-permission with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def ready(self):
        if django_version() == DjangoVersion.DJANGO_21:
            # Disable silently the package for Django => 2.1. We don't override
            # admin_site neither the default ModelAdmin.
            warnings.warn(
                'The package `admin_view_permission is deprecated in '
                'Django 2.1. Django added this functionality into the core.',
                DeprecationWarning
            )
            return

        if not isinstance(admin.site, AdminViewPermissionAdminSite):
            admin.site = AdminViewPermissionAdminSite('admin')
            admin.sites.site = admin.site

        post_migrate.connect(update_permissions) 
Example #21
Source File: backends.py    From anytask with MIT License 6 votes vote down vote up
def test_email_send_action_no_sites(self):
        """
        Test re-sending of activation emails via admin action when
        ``django.contrib.sites`` is not installed; the fallback will
        be a ``RequestSite`` instance.
        
        """
        Site._meta.installed = False
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)
        
        alice = self.backend.register(_mock_request(),
                                      username='alice',
                                      email='alice@example.com',
                                      password1='swordfish')
        
        admin_class.resend_activation_email(_mock_request(),
                                            RegistrationProfile.objects.all())
        self.assertEqual(len(mail.outbox), 2) # One on registering, one more on the resend.
        
        RegistrationProfile.objects.filter(user=alice).update(activation_key=RegistrationProfile.ACTIVATED)
        admin_class.resend_activation_email(_mock_request(),
                                            RegistrationProfile.objects.all())
        self.assertEqual(len(mail.outbox), 2) # No additional email because the account has activated.
        Site._meta.installed = True 
Example #22
Source File: backends.py    From anytask with MIT License 6 votes vote down vote up
def test_email_send_action(self):
        """
        Test re-sending of activation emails via admin action.
        
        """
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)
        
        alice = self.backend.register(_mock_request(),
                                      username='alice',
                                      email='alice@example.com',
                                      password1='swordfish')
        
        admin_class.resend_activation_email(_mock_request(),
                                            RegistrationProfile.objects.all())
        self.assertEqual(len(mail.outbox), 2) # One on registering, one more on the resend.
        
        RegistrationProfile.objects.filter(user=alice).update(activation_key=RegistrationProfile.ACTIVATED)
        admin_class.resend_activation_email(_mock_request(),
                                            RegistrationProfile.objects.all())
        self.assertEqual(len(mail.outbox), 2) # No additional email because the account has activated. 
Example #23
Source File: backends.py    From anytask with MIT License 6 votes vote down vote up
def test_email_send_action_no_sites(self):
        """
        Test re-sending of activation emails via admin action when
        ``django.contrib.sites`` is not installed; the fallback will
        be a ``RequestSite`` instance.
        
        """
        Site._meta.installed = False
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)
        
        alice = self.backend.register(_mock_request(),
                                      username='alice',
                                      email='alice@example.com',
                                      password1='swordfish')
        
        admin_class.resend_activation_email(_mock_request(),
                                            RegistrationProfile.objects.all())
        self.assertEqual(len(mail.outbox), 2) # One on registering, one more on the resend.
        
        RegistrationProfile.objects.filter(user=alice).update(activation_key=RegistrationProfile.ACTIVATED)
        admin_class.resend_activation_email(_mock_request(),
                                            RegistrationProfile.objects.all())
        self.assertEqual(len(mail.outbox), 2) # No additional email because the account has activated.
        Site._meta.installed = True 
Example #24
Source File: backends.py    From anytask with MIT License 6 votes vote down vote up
def test_email_send_action(self):
        """
        Test re-sending of activation emails via admin action.
        
        """
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)
        
        alice = self.backend.register(_mock_request(),
                                      username='alice',
                                      email='alice@example.com',
                                      password1='swordfish')
        
        admin_class.resend_activation_email(_mock_request(),
                                            RegistrationProfile.objects.all())
        self.assertEqual(len(mail.outbox), 2) # One on registering, one more on the resend.
        
        RegistrationProfile.objects.filter(user=alice).update(activation_key=RegistrationProfile.ACTIVATED)
        admin_class.resend_activation_email(_mock_request(),
                                            RegistrationProfile.objects.all())
        self.assertEqual(len(mail.outbox), 2) # No additional email because the account has activated. 
Example #25
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_use_custom_admin_site(self):
        self.assertEqual(admin.site.__class__.__name__, 'CustomAdminSite') 
Example #26
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_fk_to_self_model_not_in_admin(self):
        # FK to self, not registered with admin site. Raw ID widget should have
        # no magnifying glass link. See #16542
        subject1 = Individual.objects.create(name='Subject #1')
        Individual.objects.create(name='Child', parent=subject1)
        rel = Individual._meta.get_field('parent').remote_field

        w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
        self.assertHTMLEqual(
            w.render('individual_widget', subject1.pk, attrs={}),
            '<input type="text" name="individual_widget" value="%(subj1pk)s">'
            '&nbsp;<strong>%(subj1)s</strong>'
            % {'subj1pk': subject1.pk, 'subj1': subject1}
        ) 
Example #27
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_use_default_admin_site(self):
        self.assertEqual(admin.site.__class__.__name__, 'AdminSite') 
Example #28
Source File: test_checks.py    From django-hijack-admin with MIT License 5 votes vote down vote up
def test_check_custom_user_model(self):
            # Django doesn't re-register admins when using `override_settings`,
            # so we have to do it manually in this test case.
            admin.site.register(get_user_model(), HijackUserAdmin)

            warnings = checks.check_custom_user_model(HijackAdminConfig)
            self.assertFalse(warnings)

            admin.site.unregister(get_user_model()) 
Example #29
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_use_custom_admin_site(self):
        self.assertEqual(admin.site.__class__.__name__, 'CustomAdminSite') 
Example #30
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        admin.site = sites.site = self._old_site