Python django.contrib.admin.site() Examples

The following are 30 code examples for showing how to use django.contrib.admin.site(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.contrib.admin , or try the search function .

Example 1
Project: django-hijack-admin   Author: arteria   File: test_checks.py    License: 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
Project: anytask   Author: znick   File: backends.py    License: 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 3
Project: anytask   Author: znick   File: backends.py    License: 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 4
Project: anytask   Author: znick   File: backends.py    License: 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 5
Project: anytask   Author: znick   File: backends.py    License: 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 6
Project: django-admin-view-permission   Author: ctxis   File: apps.py    License: 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 7
Project: DCRM   Author: 82Flex   File: test_all.py    License: 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 8
Project: DCRM   Author: 82Flex   File: test_all.py    License: 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 9
Project: DCRM   Author: 82Flex   File: suit_menu.py    License: 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 10
Project: django-admin-rangefilter   Author: silentsokolov   File: tests.py    License: 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 11
Project: django-admin-rangefilter   Author: silentsokolov   File: tests.py    License: 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 12
Project: django-admin-rangefilter   Author: silentsokolov   File: tests.py    License: 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
Project: django-admin-rangefilter   Author: silentsokolov   File: tests.py    License: 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 14
Project: django-admin-rangefilter   Author: silentsokolov   File: tests.py    License: 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 15
Project: django-admin-rangefilter   Author: silentsokolov   File: tests.py    License: 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 16
Project: django-admin-rangefilter   Author: silentsokolov   File: tests.py    License: 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 17
Project: django-ra-erp   Author: ra-systems   File: suit_menu.py    License: 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 18
Project: django-adminlte-ui   Author: wuyue92tree   File: adminlte_menu.py    License: 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 19
Project: django-enum-choices   Author: HackSoftware   File: test_admin_filter.py    License: 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 20
Project: django-admin-tools   Author: django-admin-tools   File: utils.py    License: 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 21
Project: djongo   Author: nesdis   File: tests.py    License: 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 22
Project: djongo   Author: nesdis   File: tests.py    License: 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 23
Project: djongo   Author: nesdis   File: tests.py    License: 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 24
Project: django-hijack-admin   Author: arteria   File: test_checks.py    License: 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 25
Project: django-hijack-admin   Author: arteria   File: test_checks.py    License: MIT License 5 votes vote down vote up
def test_check_custom_user_model_custom_admin(self):
            class CustomAdminSite(admin.AdminSite):
                pass

            _default_site = admin.site
            admin.site = CustomAdminSite()
            admin.autodiscover()

            admin.site.register(get_user_model(), HijackUserAdmin)

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

            admin.site.unregister(get_user_model())
            admin.site = _default_site 
Example 26
Project: donation-tracker   Author: GamesDoneQuick   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def get_admin(Model):
    return admin.site._registry[Model] 
Example 27
Project: anytask   Author: znick   File: backends.py    License: MIT License 5 votes vote down vote up
def test_activation_action(self):
        """
        Test manual activation of users view admin action.
        
        """
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        alice = self.backend.register(_mock_request(),
                                      username='alice',
                                      email='alice@example.com',
                                      password1='swordfish')

        admin_class.activate_users(_mock_request(),
                                   RegistrationProfile.objects.all())
        self.failUnless(User.objects.get(username='alice').is_active) 
Example 28
Project: DCRM   Author: 82Flex   File: test_all.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_preferences_class_prepared(self):
        """
        Regardless of what happens in the background, after startup and model
        preparation the preferences.preferences object should have members for
        each of the various preferences models. When accessing the member the
        appropriate object for the current site should be returned (or
        unassociated with a site if not using sites).
        """

        # Should have MyPreferences member without
        # sites since we are not using sites.
        my_preferences = preferences.MyPreferences
        self.failIf(my_preferences.sites.all(), "Without SITE_ID should not \
have any preferences with sites.")

        # Should have MyPreferences member for current site.
        settings.SITE_ID = 1
        current_site = Site.objects.get_current()
        my_preferences = preferences.MyPreferences
        self.failUnlessEqual(current_site, my_preferences.sites.get(), "With \
SITE_ID should have preferences for current site.")

        # Should have MyPreferences member for current site.
        settings.SITE_ID = 2
        second_site, created = Site.objects.get_or_create(id=2)
        my_preferences = preferences.MyPreferences
        self.failUnlessEqual(second_site, my_preferences.sites.get(), "With \
SITE_ID should have preferences for current site.") 
Example 29
Project: DCRM   Author: 82Flex   File: test_all.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_site_cleanup(self):
        """
        There should only ever be a single preferences object per site. Thus on
        many to many changes pre-existing preferences should be cleared of
        sites already associated with current preferences object.
        """
        # When creating new preferences for a site, said site should be
        # removed from existing preference sites.
        site1 = Site.objects.create(domain="testserver")
        site2 = Site.objects.create(domain="another")

        # Add preferences for site 1.
        site1_preferences = MyPreferences.objects.create()
        site1_preferences.sites.add(site1)
        self.failUnlessEqual(site1_preferences.sites.get(), site1)

        # Now if we add another preferences object for site1, original site1
        # preferences should no longer be associated with site1.
        more_site1_preferences = MyPreferences.objects.create()
        more_site1_preferences.sites.add(site1)
        self.failIf(site1 in site1_preferences.sites.all())

        # If we add more sites to a preference,
        # it should be associated with them all.
        more_site1_preferences.sites.add(site2)
        self.failIf(site1 not in more_site1_preferences.sites.all() or site2 not in more_site1_preferences.sites.all())
        some_more_preferences = MyPreferences.objects.create()
        some_more_preferences.sites.add(site1)
        some_more_preferences.sites.add(site2)
        self.failIf(site1 in more_site1_preferences.sites.all() or site2 in more_site1_preferences.sites.all())
        # Double check that we now only have a single
        # preferences object associated with both sites.
        self.failUnlessEqual(MyPreferences.objects.filter(sites__in=[site1, site2]).distinct().get(),
                             some_more_preferences) 
Example 30
Project: django-admino   Author: erdem   File: sites.py    License: MIT License 5 votes vote down vote up
def __init__(self, django_site, name='admino'):
        self.django_site = django_site
        self._registry = {}
        self.name = name
        self._actions = {'delete_selected': actions.delete_selected}
        self._global_actions = self._actions.copy()