Python django.contrib.admin() Examples

The following are 30 code examples for showing how to use django.contrib.admin(). 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 , or try the search function .

Example 1
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
Project: django-flexible-subscriptions   Author: studybuffalo   File: test_admin.py    License: 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 3
Project: openapi-core   Author: p1c2u   File: test_django.py    License: 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 4
Project: openapi-core   Author: p1c2u   File: test_django.py    License: 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 5
Project: django-collaborative   Author: propublica   File: models.py    License: 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 6
Project: edx-enterprise   Author: edx   File: views.py    License: 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 7
Project: weixin_server   Author: duoduo369   File: admin.py    License: 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 8
Project: django-inline-actions   Author: escaped   File: admin.py    License: 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 9
Project: djongo   Author: nesdis   File: tests.py    License: 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
Project: djongo   Author: nesdis   File: tests.py    License: 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 11
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 12
Project: django-hijack-admin   Author: arteria   File: checks.py    License: MIT License 5 votes vote down vote up
def _using_hijack_admin_mixin():
    from hijack_admin.admin import HijackUserAdminMixin

    user_admin_class_name = getattr(
        settings, 'HIJACK_USER_ADMIN_CLASS_NAME', None)
    user_admin_class = user_admin_class_name \
        if user_admin_class_name else type(
            admin.site._registry.get(get_user_model(), None))

    return issubclass(user_admin_class, HijackUserAdminMixin) 
Example 13
Project: django-hijack-admin   Author: arteria   File: checks.py    License: MIT License 5 votes vote down vote up
def check_get_requests_allowed(app_configs, **kwargs):
    errors = []
    if not hijack_settings.HIJACK_ALLOW_GET_REQUESTS:
        errors.append(
            Error(
                'Hijack GET requests must be allowed for django-hijack-admin to work.',
                hint='Set HIJACK_ALLOW_GET_REQUESTS to True.',
                obj=None,
                id='hijack_admin.E001',
            )
        )
    return errors 
Example 14
Project: django-hijack-admin   Author: arteria   File: checks.py    License: MIT License 5 votes vote down vote up
def check_custom_user_model(app_configs, **kwargs):
    warnings = []
    if (settings.AUTH_USER_MODEL != DEFAULT_AUTH_USER_MODEL and
            not _using_hijack_admin_mixin()):
        warnings.append(
            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',
            )
        )
    return warnings 
Example 15
Project: rainmap-lite   Author: cldrn   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def clear_logs(request):
    """Clear admin activity logs if user has permissions"""

    if not request.user.is_authenticated(): # should be applied to anything under /console
        return redirect('login')

    if request.user.has_perm('admin.delete_logentry'):
        LogEntry.objects.all().filter(user__pk=request.user.id).delete()
        messages.info(request, 'Successfully cleared admin activity logs.', fail_silently=True)
    else:
        messages.warning(request, 'Unable to clear the admin activity logs.', fail_silently=True)

    return redirect('admin:index') 
Example 16
Project: Django-Merged-Inlines   Author: MattBroach   File: tests.py    License: MIT License 5 votes vote down vote up
def test_basic_merged_view(self):
        """
        With no special settings, the MergedInlineAdmin should order the
        merged inlines by ID
        """
        response = self.client.get(reverse('admin:tests_author_change', args=(1,)))

        self.assertEqual(response.status_code, 200)
        self.assertStringOrder(response, [
            'Romeo and Juliet',
            'Shall I compare thee to a summer',
            'A Midsummer Night',
            'As a decrepit father takes delight',
            'Julius Caesar',
        ]) 
Example 17
Project: Django-Merged-Inlines   Author: MattBroach   File: tests.py    License: MIT License 5 votes vote down vote up
def test_merged_by_custom_field_view(self):
        """
        Specifying a particular merging field
        """
        response = self.client.get(reverse('admin:tests_kingdom_change', args=(1,)))

        self.assertEqual(response.status_code, 200)
        self.assertStringOrder(response, [
            'Bronn',
            'Joffrey Baratheon',
            'Rob Stark',
            'The Hound',
            'Tommen Baratheon'
        ]) 
Example 18
Project: Django-Merged-Inlines   Author: MattBroach   File: tests.py    License: MIT License 5 votes vote down vote up
def test_custom_field_order_view(self):
        """
        Check that a custom form field ordering is in effect
        """
        response = self.client.get(reverse('admin:tests_kingdom_change', args=(1,)))

        self.assertEqual(response.status_code, 200)
        self.assertStringOrder(response, [
            '<th>Alive',
            '<th>Name',
            '<th>House'
        ]) 
Example 19
Project: GTDWeb   Author: lanbing510   File: views.py    License: GNU General Public License v2.0 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        if not utils.docutils_is_available:
            # Display an error message for people without docutils
            self.template_name = 'admin_doc/missing_docutils.html'
            return self.render_to_response(admin.site.each_context(request))
        return super(BaseAdminDocsView, self).dispatch(request, *args, **kwargs) 
Example 20
Project: GTDWeb   Author: lanbing510   File: views.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_context_data(self, **kwargs):
        kwargs.update({'root_path': urlresolvers.reverse('admin:index')})
        kwargs.update(admin.site.each_context(self.request))
        return super(BaseAdminDocsView, self).get_context_data(**kwargs) 
Example 21
Project: DCRM   Author: 82Flex   File: admin.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'title':
            kwargs['widget'] = AdminTextInputWidget
        return super(FluentCommentsAdmin, self).formfield_for_dbfield(db_field, **kwargs)


# Replace the old admin screen. 
Example 22
Project: DCRM   Author: 82Flex   File: statistics.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def statistics_view(request):
    """
    :param request: Django Request
    :return: Django HttpResponse
    :rtype: HttpResponse
    """
    if request.method == 'GET':
        context = admin.site.each_context(request)
        context.update({
            'title': _('Statistics'),
            'db_status': db_status(),
            'stat': statistics(),
            'settings': preferences.Setting,
        })

        template = 'admin/help/statistics.html'
        return render(request, template, context)
    else:
        if 'action' in request.POST and request.POST['action'] == 'clean_all':
            result_dict = {}
            try:
                # cache clear
                cache.clear()
                # remove all temporarily files
                if os.path.exists(TEMP_ROOT):
                    shutil.rmtree(TEMP_ROOT)
                    os.mkdir(TEMP_ROOT)
                else:
                    os.mkdir(TEMP_ROOT)
                result_dict = {"status": True}
                return HttpResponse(json.dumps(result_dict), content_type='application/json')
            except Exception as e:
                # error handler
                result_dict.update({
                    "success": False,
                    "exception": str(e)
                })
                return HttpResponse(json.dumps(result_dict), content_type='application/json') 
Example 23
Project: DCRM   Author: 82Flex   File: about.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def about_view(request):
    """
    :param request: Django Request
    :return: Django HttpResponse
    :rtype: HttpResponse
    """
    context = admin.site.each_context(request)
    context.update({
        'title': _('About'),
        'version': "4.1",
    })

    template = 'admin/help/about.html'
    return render(request, template, context) 
Example 24
Project: django-x509   Author: openwisp   File: test_admin.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ca_url(self):
        ma = self.cert_admin(Cert, self.site)
        self.assertEqual(
            ma.ca_url(self.cert), f'<a href="/admin/{self.app_label}/ca/1/change/"></a>'
        ) 
Example 25
Project: django-seo   Author: whyflyru   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_model_in_admin(model, admin_class=None):
    """
    Register model in Django admin interface
    """
    from django.contrib import admin
    admin.site.register(model, admin_class)

    _reload_urlconf() 
Example 26
Project: django-seo   Author: whyflyru   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        # Create and login a superuser for the admin
        user = User(username="admin", is_staff=True, is_superuser=True)
        user.set_password("admin")
        user.save()
        self.client.login(username="admin", password="admin") 
Example 27
Project: django-seo   Author: whyflyru   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_inline_smoke(self):
        """ Tests that no error is raised when viewing an inline in the admin.
        """
        path = '/admin/userapp/page/add/'
        try:
            response = self.client.get(path)
        except Exception as e:
            self.fail(u"Exception raised at '%s': %s" % (path, e))
        self.assertEqual(response.status_code, 200) 
Example 28
Project: django-seo   Author: whyflyru   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_inline_add(self):
        path = '/admin/userapp/tag/add/'
        data = {
            "name": "Test",
            "djangoseo-coveragemodelinstance-_content_type-_object_id-0-title": "test",
            "djangoseo-coveragemodelinstance-_content_type-_object_id-TOTAL_FORMS": "1",
            "djangoseo-coveragemodelinstance-_content_type-_object_id-INITIAL_FORMS": "0",
            "djangoseo-coveragemodelinstance-_content_type-_object_id-MAX_NUM_FORMS": "1",
            "djangoseo-withsitesmodelinstance-_content_type-_object_id-TOTAL_FORMS": "1",
            "djangoseo-withsitesmodelinstance-_content_type-_object_id-INITIAL_FORMS": "0",
            "djangoseo-withsitesmodelinstance-_content_type-_object_id-MAX_NUM_FORMS": "1",
        }

        try:
            response = self.client.post(path, data, follow=True)
        except Exception as e:
            self.fail("Exception raised at '%s': %s" % (path, e))
        self.assertEqual(response.status_code, 200)

        path = '/admin/djangoseo/coveragemodel/add/'
        data = {
            "title": "Testing",
            "_content_type": u'3',
        }

        try:
            response = self.client.post(path, data, follow=True)
        except Exception as e:
            self.fail(u"Exception raised at '%s': %s" % (path, e))
        self.assertEqual(response.status_code, 200) 
Example 29
Project: django-seo   Author: whyflyru   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_autoinline(self):
        for model in ('tag', 'page', 'product'):
            path = '/alt-admin/userapp/%s/add/' % model
            try:
                response = self.client.get(path)
            except Exception as e:
                self.fail("Exception raised at '%s': %s" % (path, e))
            self.assertContains(response, "seo-coveragemodelinstance-_content_type", status_code=200)
            self.assertNotContains(response, "seo-withsitesmodelinstance-_content_type")
            self.assertContains(response, "seo-withseomodelsmodelinstance-_content_type", status_code=200) 
Example 30
Project: django-admin-rangefilter   Author: silentsokolov   File: filter.py    License: MIT License 5 votes vote down vote up
def choices(self, cl):
        yield {
            # slugify converts any non-unicode characters to empty characters
            # but system_name is required, if title converts to empty string use id
            # https://github.com/silentsokolov/django-admin-rangefilter/issues/18
            'system_name': force_str(slugify(self.title) if slugify(self.title) else id(self.title)),
            'query_string': cl.get_query_string(
                {}, remove=self._get_expected_fields()
            )
        }