Python django.contrib.admin() Examples

The following are 30 code examples of django.contrib.admin(). 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 , or try the search function .
Example #1
Source File: middleware.py    From django-modeladmin-reorder with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def process_template_response(self, request, response):
        try:
            url = resolve(request.path_info)
        except Resolver404:
            return response
        if not url.app_name == 'admin' and \
                url.url_name not in ['index', 'app_list']:
            # current view is not a django admin index
            # or app_list view, bail out!
            return response

        try:
            app_list = response.context_data['app_list']
        except KeyError:
            # there is no app_list! nothing to reorder
            return response

        self.init_config(request, app_list)
        ordered_app_list = self.get_app_list()
        response.context_data['app_list'] = ordered_app_list
        return response 
Example #2
Source File: admin.py    From django-inline-actions with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_inline_actions(self, request, obj=None):
        """
        Returns a list of all actions for this Admin.
        """
        # If self.actions is explicitly set to None that means that we don't
        # want *any* actions enabled on this page.
        if self.inline_actions is None:
            return []

        actions = []

        # Gather actions from the inline admin and all parent classes,
        # starting with self and working back up.
        for klass in self.__class__.mro()[::-1]:
            class_actions = getattr(klass, 'inline_actions', [])
            # Avoid trying to iterate over None
            if not class_actions:
                continue

            for action in class_actions:
                if action not in actions:
                    actions.append(action)

        return actions 
Example #3
Source File: admin.py    From weixin_server with MIT License 6 votes vote down vote up
def revert(self, request, queryset):
        """
        Admin action to revert a configuration back to the selected value
        """
        if queryset.count() != 1:
            self.message_user(request, _("Please select a single configuration to revert to."))
            return
        target = queryset[0]
        target.id = None
        target.changed_by = request.user
        target.save(action_type='create')
        self.message_user(request, _("Reverted configuration."))
        return HttpResponseRedirect(
            reverse(
                'admin:{}_{}_change'.format(
                    self.model._meta.app_label,
                    self.model._meta.model_name,
                ),
                args=(target.id,),
            )
        ) 
Example #4
Source File: test_admin.py    From django-flexible-subscriptions with GNU General Public License v3.0 6 votes vote down vote up
def test_admin_excluded_when_false_in_settings():
    """Tests that admin views are not loaded when disabled in settings."""
    # pylint: disable=protected-access
    reload(subscription_admin)

    try:
        admin.site._registry[models.SubscriptionPlan]
    except KeyError:
        assert True
    else:
        assert False

    try:
        admin.site._registry[models.UserSubscription]
    except KeyError:
        assert True
    else:
        assert False
    try:
        admin.site._registry[models.SubscriptionTransaction]
    except KeyError:
        assert True
    else:
        assert False 
Example #5
Source File: test_django.py    From openapi-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_no_resolver(self, request_factory):
        request = request_factory.get('/admin/')

        openapi_request = DjangoOpenAPIRequest(request)

        path = {}
        query = {}
        headers = {
            'Cookie': '',
        }
        cookies = {}
        assert openapi_request.parameters == RequestParameters(
            path=path,
            query=query,
            header=headers,
            cookie=cookies,
        )
        assert openapi_request.method == request.method.lower()
        assert openapi_request.full_url_pattern == \
            request._current_scheme_host + request.path
        assert openapi_request.body == request.body
        assert openapi_request.mimetype == request.content_type 
Example #6
Source File: test_django.py    From openapi-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_simple(self, request_factory):
        from django.urls import resolve
        request = request_factory.get('/admin/')
        request.resolver_match = resolve('/admin/')

        openapi_request = DjangoOpenAPIRequest(request)

        path = {}
        query = {}
        headers = {
            'Cookie': '',
        }
        cookies = {}
        assert openapi_request.parameters == RequestParameters(
            path=path,
            query=query,
            header=headers,
            cookie=cookies,
        )
        assert openapi_request.method == request.method.lower()
        assert openapi_request.full_url_pattern == \
            request._current_scheme_host + request.path
        assert openapi_request.body == request.body
        assert openapi_request.mimetype == request.content_type 
Example #7
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_delete_str_in_model_admin(self):
        """
        Test if the admin delete page shows the correct string representation
        for a proxy model.
        """
        user = TrackerUser.objects.get(name='Django Pony')
        proxy = ProxyTrackerUser.objects.get(name='Django Pony')

        user_str = 'Tracker user: <a href="%s">%s</a>' % (
            reverse('admin_proxy:proxy_models_trackeruser_change', args=(user.pk,)), user
        )
        proxy_str = 'Proxy tracker user: <a href="%s">%s</a>' % (
            reverse('admin_proxy:proxy_models_proxytrackeruser_change', args=(proxy.pk,)), proxy
        )

        self.client.force_login(self.superuser)
        response = self.client.get(reverse('admin_proxy:proxy_models_trackeruser_delete', args=(user.pk,)))
        delete_str = response.context['deleted_objects'][0]
        self.assertEqual(delete_str, user_str)
        response = self.client.get(reverse('admin_proxy:proxy_models_proxytrackeruser_delete', args=(proxy.pk,)))
        delete_str = response.context['deleted_objects'][0]
        self.assertEqual(delete_str, proxy_str) 
Example #8
Source File: views.py    From edx-enterprise with GNU Affero General Public License v3.0 6 votes vote down vote up
def _build_context(self, request, customer_uuid):
        """
        Build common context parts used by different handlers in this view.
        """
        # TODO: pylint acts stupid - find a way around it without suppressing
        enterprise_customer = EnterpriseCustomer.objects.get(uuid=customer_uuid)  # pylint: disable=no-member

        search_keyword = self.get_search_keyword(request)
        linked_learners = self.get_enterprise_customer_user_queryset(request, search_keyword, customer_uuid)
        pending_linked_learners = self.get_pending_users_queryset(search_keyword, customer_uuid)

        context = {
            self.ContextParameters.ENTERPRISE_CUSTOMER: enterprise_customer,
            self.ContextParameters.PENDING_LEARNERS: pending_linked_learners,
            self.ContextParameters.LEARNERS: linked_learners,
            self.ContextParameters.SEARCH_KEYWORD: search_keyword or '',
            self.ContextParameters.ENROLLMENT_URL: settings.LMS_ENROLLMENT_API_PATH,
        }
        context.update(admin.site.each_context(request))
        context.update(self._build_admin_context(request, enterprise_customer))
        return context 
Example #9
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_delete_str_in_model_admin(self):
        """
        Test if the admin delete page shows the correct string representation
        for a proxy model.
        """
        user = TrackerUser.objects.get(name='Django Pony')
        proxy = ProxyTrackerUser.objects.get(name='Django Pony')

        user_str = 'Tracker user: <a href="%s">%s</a>' % (
            reverse('admin_proxy:proxy_models_trackeruser_change', args=(user.pk,)), user
        )
        proxy_str = 'Proxy tracker user: <a href="%s">%s</a>' % (
            reverse('admin_proxy:proxy_models_proxytrackeruser_change', args=(proxy.pk,)), proxy
        )

        self.client.force_login(self.superuser)
        response = self.client.get(reverse('admin_proxy:proxy_models_trackeruser_delete', args=(user.pk,)))
        delete_str = response.context['deleted_objects'][0]
        self.assertEqual(delete_str, user_str)
        response = self.client.get(reverse('admin_proxy:proxy_models_proxytrackeruser_delete', args=(proxy.pk,)))
        delete_str = response.context['deleted_objects'][0]
        self.assertEqual(delete_str, proxy_str) 
Example #10
Source File: models.py    From django-collaborative with MIT License 6 votes vote down vote up
def delete(self, **kwargs):
        # first drop the table, we have to do this first, else
        # django will complain about no content type existing
        Model = apps.get_model("django_models_from_csv", self.name)
        ModelSchemaEditor().drop_table(Model)

        # then remove django app and content-types/permissions
        app_config = apps.get_app_config("django_models_from_csv")
        wipe_models_and_permissions(app_config, self.name)

        # finally kill the row
        super().delete(**kwargs)

        # delete it from the django app registry
        try:
            del apps.all_models["django_models_from_csv"][self.name]
        except KeyError as err:
            raise LookupError("'{}' not found.".format(self.name))

        # Unregister the model from the admin, before we wipe it out
        try:
            admin.site.unregister(Model)
        except admin.sites.NotRegistered:
            pass 
Example #11
Source File: test_admin.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_admin_site_register_tethys_app_admin(self):
        from django.contrib import admin
        registry = admin.site._registry
        self.assertIn(TethysApp, registry)
        self.assertIsInstance(registry[TethysApp], TethysAppAdmin) 
Example #12
Source File: test_admin.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_TethysAppSettingInline(self):
        expected_template = 'tethys_portal/admin/edit_inline/tabular.html'
        TethysAppSettingInline.model = mock.MagicMock()
        ret = TethysAppSettingInline(mock.MagicMock(), mock.MagicMock())
        self.assertEqual(expected_template, ret.template) 
Example #13
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_cascade_delete_proxy_model_admin_warning(self):
        """
        Test if admin gives warning about cascade deleting models referenced
        to concrete model by deleting proxy object.
        """
        tracker_user = TrackerUser.objects.all()[0]
        base_user = BaseUser.objects.all()[0]
        issue = Issue.objects.all()[0]
        with self.assertNumQueries(6):
            collector = admin.utils.NestedObjects('default')
            collector.collect(ProxyTrackerUser.objects.all())
        self.assertIn(tracker_user, collector.edges.get(None, ()))
        self.assertIn(base_user, collector.edges.get(None, ()))
        self.assertIn(issue, collector.edges.get(tracker_user, ())) 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_cascade_delete_proxy_model_admin_warning(self):
        """
        Test if admin gives warning about cascade deleting models referenced
        to concrete model by deleting proxy object.
        """
        tracker_user = TrackerUser.objects.all()[0]
        base_user = BaseUser.objects.all()[0]
        issue = Issue.objects.all()[0]
        with self.assertNumQueries(6):
            collector = admin.utils.NestedObjects('default')
            collector.collect(ProxyTrackerUser.objects.all())
        self.assertIn(tracker_user, collector.edges.get(None, ()))
        self.assertIn(base_user, collector.edges.get(None, ()))
        self.assertIn(issue, collector.edges.get(tracker_user, ())) 
Example #15
Source File: middleware.py    From django-modeladmin-reorder with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def init_config(self, request, app_list):
        self.request = request
        self.app_list = app_list

        self.config = getattr(settings, 'ADMIN_REORDER', None)
        if not self.config:
            # ADMIN_REORDER settings is not defined.
            raise ImproperlyConfigured('ADMIN_REORDER config is not defined.')

        if not isinstance(self.config, (tuple, list)):
            raise ImproperlyConfigured(
                'ADMIN_REORDER config parameter must be tuple or list. '
                'Got {config}'.format(config=self.config))

        admin_index = admin.site.index(request)
        try:
            # try to get all installed models
            app_list = admin_index.context_data['app_list']
        except KeyError:
            # use app_list from context if this fails
            pass

        # Flatten all models from apps
        self.models_list = []
        for app in app_list:
            for model in app['models']:
                model['model_name'] = self.get_model_name(
                    app['app_label'], model['object_name'])
                self.models_list.append(model) 
Example #16
Source File: admin.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 5 votes vote down vote up
def display_users(self, obj):
        links = []
        for user in obj.user_set.all():
            ct = ContentType.objects.get_for_model(user)
            rule_name = f"admin:{ct.app_label}_{ct.model}_change"
            url = reverse(rule_name, args=(user.id,))
            user_name = (
                    f"{user.first_name} {user.last_name}".strip()
                    or user.username)
            links.append(f"""
            <a href="{url}" target="_blank">{user_name}</a>
            """)
        return mark_safe("<br />".join(links)) 
Example #17
Source File: admin.py    From Django-2-Web-Development-Cookbook-Third-Edition with MIT License 5 votes vote down vote up
def display_users(self, obj):
        links = []
        for user in obj.user_set.all():
            ct = ContentType.objects.get_for_model(user)
            rule_name = f"admin:{ct.app_label}_{ct.model}_change"
            url = reverse(rule_name, args=(user.id,))
            user_name = (
                    f"{user.first_name} {user.last_name}".strip()
                    or user.username)
            links.append(f"""
            <a href="{url}" target="_blank">{user_name}</a>
            """)
        return mark_safe("<br />".join(links)) 
Example #18
Source File: test_admin.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_TethysAppAdmin_manage_app_storage(self, mock_convert, mock_get_quota):
        ret = TethysAppAdmin(mock.MagicMock(), mock.MagicMock())
        app = mock.MagicMock()
        app.id = 1
        mock_convert.return_value = '0 bytes'
        mock_get_quota.return_value = {'quota': None}
        url = reverse('admin:clear_workspace', kwargs={'app_id': app.id})

        expected_html = format_html("""
                <span>{} of {}</span>
                <a id="clear-workspace" class="btn btn-danger btn-sm"
                href="{url}">
                Clear Workspace</a>
                """.format('0 bytes', "&#8734;", url=url))
        actual_html = ret.manage_app_storage(app)

        self.assertEquals(expected_html.replace(" ", ""), actual_html.replace(" ", ""))

        mock_convert.return_value = '0 bytes'
        mock_get_quota.return_value = {'quota': 5, 'units': 'gb'}
        url = reverse('admin:clear_workspace', kwargs={'app_id': app.id})

        expected_html = format_html("""
                        <span>{} of {}</span>
                        <a id="clear-workspace" class="btn btn-danger btn-sm"
                        href="{url}">
                        Clear Workspace</a>
                        """.format('0 bytes', "0 bytes", url=url))
        actual_html = ret.manage_app_storage(app)

        self.assertEquals(expected_html.replace(" ", ""), actual_html.replace(" ", "")) 
Example #19
Source File: models.py    From django-collaborative with MIT License 5 votes vote down vote up
def do_migrations(self):
        """
        Do a custom migration without leaving any migration files
        around.
        """
        old_desc = DynamicModel.objects.filter(name=self.name).first()
        try:
            OldModel = apps.get_model("django_models_from_csv", self.name)
        except LookupError:
            OldModel = None

        # TODO: for some reason force_new=True (removed now, but forces re-
        # creation of the model class) makes the model show up multiple
        # times in the admin. but setting this to False makes the meta
        # schema migrations not work properly w/o restarting the system.
        # I need to fix this, along with custom meta in general, but for
        # now we need to reinstate sane working defaults.
        NewModel = construct_model(self)
        new_desc = self
        ModelSchemaEditor(OldModel).update_table(NewModel)

        for new_field in NewModel._meta.fields:
            if new_field.name == "id":
                continue
            old_field = self.find_old_field(OldModel, new_field)
            if old_field:
                FieldSchemaEditor(old_field).update_column(NewModel, new_field) 
Example #20
Source File: test_admin.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_admin_site_register_custom_user(self, mock_user_admin):
        from django.contrib import admin
        ret = CustomUser(mock.MagicMock(), mock.MagicMock())
        ret.change_view(mock.MagicMock())
        mock_user_admin.assert_called()
        self.assertEqual([UserQuotasSettingInline], ret.inlines)
        registry = admin.site._registry
        self.assertIn(User, registry)
        self.assertIsInstance(registry[User], CustomUser) 
Example #21
Source File: admin.py    From weixin_server with MIT License 5 votes vote down vote up
def delete_weixin_menu(self, request, queryset):
        menu = self.model()
        menu.changed_by = request.user
        menu.data = '{}'
        menu.enabled = False
        menu.save(action_type='delete')
        self.message_user(request, _("Delete Weixin Menu."))
        return HttpResponseRedirect(reverse('admin:{}_{}_changelist'.format(
            self.model._meta.app_label, self.model._meta.model_name,))) 
Example #22
Source File: admin.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def delete_view(self, request, object_id, extra_context=None):
        return HttpResponseRedirect(reverse('admin:sites_site_change', args=[settings.SITE_ID]))


# we don't want comments to be accessible via the admin interface 
Example #23
Source File: admin.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def add_view(self, request, form_url='', extra_context=None):
        return HttpResponseRedirect(reverse('admin:sites_site_change', args=[settings.SITE_ID])) 
Example #24
Source File: admin.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def delete_model(self, request, obj):
        delete_user(obj)


# user admin extended functionality 
Example #25
Source File: admin.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def response_delete(self, request, obj_display, obj_id):
        result = super().response_delete(request, obj_display, obj_id)

        if not _modifying_myself(request, obj_id):
            return result

        # user doesn't exist anymore so go to the index page
        # instead of returning to the user admin page
        return HttpResponseRedirect(reverse('core-views-index')) 
Example #26
Source File: admin.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def user_change_password(self, request, id, form_url=''):  # pylint: disable=redefined-builtin
        return HttpResponseRedirect(reverse('admin:password_change')) 
Example #27
Source File: views.py    From edx-enterprise with GNU Affero General Public License v3.0 5 votes vote down vote up
def _build_admin_context(request, customer):
        """
        Build common admin context.
        """
        opts = customer._meta
        codename = get_permission_codename("change", opts)
        has_change_permission = request.user.has_perm("%s.%s" % (opts.app_label, codename))
        return {
            "has_change_permission": has_change_permission,
            "opts": opts
        } 
Example #28
Source File: views.py    From edx-enterprise with GNU Affero General Public License v3.0 5 votes vote down vote up
def _build_context(self, request, enterprise_customer_uuid):
        """
        Build common context parts used by different handlers in this view.
        """
        enterprise_customer = EnterpriseCustomer.objects.get(uuid=enterprise_customer_uuid)  # pylint: disable=no-member

        context = {
            self.ContextParameters.ENTERPRISE_CUSTOMER: enterprise_customer,
        }
        context.update(admin.site.each_context(request))
        context.update(self._build_admin_context(request, enterprise_customer))
        return context 
Example #29
Source File: views.py    From edx-enterprise with GNU Affero General Public License v3.0 5 votes vote down vote up
def _build_admin_context(request, customer):
        """
        Build common admin context.
        """
        opts = customer._meta
        codename = get_permission_codename('change', opts)
        has_change_permission = request.user.has_perm('%s.%s' % (opts.app_label, codename))
        return {
            'has_change_permission': has_change_permission,
            'opts': opts
        } 
Example #30
Source File: test_admin.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_admin_site_register_tethys_app_extension(self):
        from django.contrib import admin
        registry = admin.site._registry
        self.assertIn(TethysExtension, registry)
        self.assertIsInstance(registry[TethysExtension], TethysExtensionAdmin)