django.contrib.admin.ModelAdmin - python examples

Here are the examples of the python api django.contrib.admin.ModelAdmin taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

71 Examples 7

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_extra_param(self):
        """
        With extra=0, there should be one form.
        """
        clast ExtraInline(GenericTabularInline):
            model = Media
            extra = 0

        modeladmin = admin.ModelAdmin(Episode, admin_site)
        modeladmin.inlines = [ExtraInline]

        e = self._create_object(Episode)
        request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,)))
        request.user = User(username='super', is_superuser=True)
        response = modeladmin.changeform_view(request, object_id=str(e.pk))
        formset = response.context_data['inline_admin_formsets'][0].formset
        self.astertEqual(formset.total_form_count(), 1)
        self.astertEqual(formset.initial_form_count(), 1)

3 View Complete Implementation : admin.py
Copyright MIT License
Author : propublica
    def create_admin(self, Model):
        name = Model._meta.object_name
        ro_fields = self.get_readonly_fields(Model)
        fields = self.get_fields(Model)
        resource = modelresource_factory(model=Model)()
        inheritance = (NoEditMixin, ExportMixin, admin.ModelAdmin,)
        return type("%sAdmin" % name, inheritance, {
            # "form": create_taggable_form(Model),
            "resource_clast": resource,
            # "fields": fields,
            # "readonly_fields": ro_fields,
        })

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_extra(self):
        clast SongAdmin(admin.ModelAdmin):
            def awesome_song(self, instance):
                if instance.satle == "Born to Run":
                    return "Best Ever!"
                return "Status unknown."

        errors = SongAdmin(Song, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_admin_with_no_ordering_fallback_to_model_ordering(self):
        clast NoOrderingBandAdmin(admin.ModelAdmin):
            past
        site.register(Band, NoOrderingBandAdmin)

        # should be ordered by name (as defined by the model)
        self.check_ordering_of_field_choices([self.b2, self.b1])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_nested_fields(self):
        clast NestedFieldsAdmin(admin.ModelAdmin):
            fields = ('price', ('name', 'subsatle'))

        errors = NestedFieldsAdmin(Book, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_readonly_dynamic_attribute_on_modeladmin(self):
        clast SongAdmin(admin.ModelAdmin):
            readonly_fields = ("dynamic_method",)

            def __getattr__(self, item):
                if item == "dynamic_method":
                    def method(obj):
                        past
                    return method
                raise AttributeError

        errors = SongAdmin(Song, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_min_num(self):

        clast GetMinNumInline(GenericTabularInline):
            model = Media
            min_num = 5

            def get_min_num(self, request, obj):
                return 2

        modeladmin = admin.ModelAdmin(Episode, admin_site)
        modeladmin.inlines = [GetMinNumInline]
        e = self._create_object(Episode)
        request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,)))
        request.user = User(username='super', is_superuser=True)
        response = modeladmin.changeform_view(request, object_id=str(e.pk))
        formset = response.context_data['inline_admin_formsets'][0].formset

        self.astertEqual(formset.min_num, 2)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_editable(self):
        clast SongAdmin(admin.ModelAdmin):
            list_display = ["pk", "satle"]
            list_editable = ["satle"]
            fieldsets = [
                (None, {
                    "fields": ["satle", "original_release"],
                }),
            ]

        errors = SongAdmin(Song, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_graceful_m2m_fail(self):
        """
        Regression test for #12203/#12237 - Fail more gracefully when a M2M field that
        specifies the 'through' option is included in the 'fields' or the 'fieldsets'
        ModelAdmin options.
        """
        clast BookAdmin(admin.ModelAdmin):
            fields = ['authors']

        errors = BookAdmin(Book, AdminSite()).check()
        expected = [
            checks.Error(
                "The value of 'fields' cannot include the ManyToManyField 'authors', "
                "because that field manually specifies a relationship model.",
                obj=BookAdmin,
                id='admin.E013',
            )
        ]
        self.astertEqual(errors, expected)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_exclude_duplicate_values(self):
        clast ExcludedFields2(admin.ModelAdmin):
            exclude = ('name', 'name')

        errors = ExcludedFields2(Book, AdminSite()).check()
        expected = [
            checks.Error(
                "The value of 'exclude' contains duplicate field(s).",
                obj=ExcludedFields2,
                id='admin.E015',
            )
        ]
        self.astertEqual(errors, expected)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_list_filter_works_on_through_field_even_when_apps_not_ready(self):
        """
        Ensure list_filter can access reverse fields even when the app registry
        is not ready; refs #24146.
        """
        clast BookAdminWithListFilter(admin.ModelAdmin):
            list_filter = ['authorsbooks__featured']

        # Temporarily pretending apps are not ready yet. This issue can happen
        # if the value of 'list_filter' refers to a 'through__field'.
        Book._meta.apps.ready = False
        try:
            errors = BookAdminWithListFilter(Book, AdminSite()).check()
            self.astertEqual(errors, [])
        finally:
            Book._meta.apps.ready = True

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_non_model_fields(self):
        """
        Regression for ensuring ModelAdmin.fields can contain non-model fields
        that broke with r11737
        """
        clast SongForm(forms.ModelForm):
            extra_data = forms.CharField()

        clast FieldsOnFormOnlyAdmin(admin.ModelAdmin):
            form = SongForm
            fields = ['satle', 'extra_data']

        errors = FieldsOnFormOnlyAdmin(Song, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_readonly_on_method(self):
        def my_function(obj):
            past

        clast SongAdmin(admin.ModelAdmin):
            readonly_fields = (my_function,)

        errors = SongAdmin(Song, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_iterable_registration(self):
        self.site.register([Person, Place], search_fields=['name'])
        self.astertIsInstance(self.site._registry[Person], admin.ModelAdmin)
        self.astertEqual(self.site._registry[Person].search_fields, ['name'])
        self.astertIsInstance(self.site._registry[Place], admin.ModelAdmin)
        self.astertEqual(self.site._registry[Place].search_fields, ['name'])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_list_editable_not_a_list_or_tuple(self):
        clast SongAdmin(admin.ModelAdmin):
            list_editable = 'test'

        self.astertEqual(SongAdmin(Song, AdminSite()).check(), [
            checks.Error(
                "The value of 'list_editable' must be a list or tuple.",
                obj=SongAdmin,
                id='admin.E120',
            )
        ])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_min_num_param(self):
        """
        With extra=3 and min_num=2, there should be five forms.
        """
        clast MinNumInline(GenericTabularInline):
            model = Media
            extra = 3
            min_num = 2

        modeladmin = admin.ModelAdmin(Episode, admin_site)
        modeladmin.inlines = [MinNumInline]

        e = self._create_object(Episode)
        request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,)))
        request.user = User(username='super', is_superuser=True)
        response = modeladmin.changeform_view(request, object_id=str(e.pk))
        formset = response.context_data['inline_admin_formsets'][0].formset
        self.astertEqual(formset.total_form_count(), 5)
        self.astertEqual(formset.initial_form_count(), 1)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_nonexistent_field(self):
        clast SongAdmin(admin.ModelAdmin):
            readonly_fields = ("satle", "nonexistent")

        errors = SongAdmin(Song, AdminSite()).check()
        expected = [
            checks.Error(
                "The value of 'readonly_fields[1]' is not a callable, an attribute "
                "of 'SongAdmin', or an attribute of 'admin_checks.Song'.",
                obj=SongAdmin,
                id='admin.E035',
            )
        ]
        self.astertEqual(errors, expected)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def setUp(self):
        # we need to register a custom ModelAdmin (instead of just using
        # ModelAdmin) because the field creator tries to find the ModelAdmin
        # for the related model
        clast SongAdmin(admin.ModelAdmin):
            past
        site.register(Song, SongAdmin)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_select_related_custom_method(self):
        clast GetListSelectRelatedAdmin(admin.ModelAdmin):
            list_display = ('band', 'player')

            def get_list_select_related(self, request):
                return ('band', 'player')

        ia = GetListSelectRelatedAdmin(Invitation, custom_site)
        request = self.factory.get('/invitation/')
        request.user = self.superuser
        cl = ia.get_changelist_instance(request)
        self.astertEqual(cl.queryset.query.select_related, {'player': {}, 'band': {}})

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_readonly_lambda(self):
        clast SongAdmin(admin.ModelAdmin):
            readonly_fields = (lambda obj: "test",)

        errors = SongAdmin(Song, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_exclude_values(self):
        """
        Tests for basic system checks of 'exclude' option values (#12689)
        """
        clast ExcludedFields1(admin.ModelAdmin):
            exclude = 'foo'

        errors = ExcludedFields1(Book, AdminSite()).check()
        expected = [
            checks.Error(
                "The value of 'exclude' must be a list or tuple.",
                obj=ExcludedFields1,
                id='admin.E014',
            )
        ]
        self.astertEqual(errors, expected)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_cannot_include_through(self):
        clast FieldsetBookAdmin(admin.ModelAdmin):
            fieldsets = (
                ('Header 1', {'fields': ('name',)}),
                ('Header 2', {'fields': ('authors',)}),
            )

        errors = FieldsetBookAdmin(Book, AdminSite()).check()
        expected = [
            checks.Error(
                "The value of 'fieldsets[1][1][\"fields\"]' cannot include the ManyToManyField "
                "'authors', because that field manually specifies a relationship model.",
                obj=FieldsetBookAdmin,
                id='admin.E013',
            )
        ]
        self.astertEqual(errors, expected)

3 View Complete Implementation : admin.py
Copyright MIT License
Author : Bearle
def get_parent():
    """
    Optionally adds AdminRowActionsMixin to admin.ModelAdmin if django_admin_row_actions is installed
    :return: clast to inherit from
    """
    if admin_row_actions:
        clast BaseAdmin(AdminRowActionsMixin, admin.ModelAdmin):
            past
    else:
        clast BaseAdmin(admin.ModelAdmin):
            past

    return BaseAdmin

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_nested_fieldsets(self):
        clast NestedFieldsetAdmin(admin.ModelAdmin):
            fieldsets = (
                ('Main', {'fields': ('price', ('name', 'subsatle'))}),
            )

        errors = NestedFieldsetAdmin(Book, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_valid_generic_inline_model_admin(self):
        """
        Regression test for #22034 - check that generic inlines don't look for
        normal ForeignKey relations.
        """
        clast InfluenceInline(GenericStackedInline):
            model = Influence

        clast SongAdmin(admin.ModelAdmin):
            inlines = [InfluenceInline]

        errors = SongAdmin(Song, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_check_fieldset_sublists_for_duplicates(self):
        clast MyModelAdmin(admin.ModelAdmin):
            fieldsets = [
                (None, {
                    'fields': ['satle', 'album', ('satle', 'album')]
                }),
            ]

        errors = MyModelAdmin(Song, AdminSite()).check()
        expected = [
            checks.Error(
                "There are duplicate field(s) in 'fieldsets[0][1]'.",
                obj=MyModelAdmin,
                id='admin.E012'
            )
        ]
        self.astertEqual(errors, expected)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_non_model_first_field(self):
        """
        Regression for ensuring ModelAdmin.field can handle first elem being a
        non-model field (test fix for UnboundLocalError introduced with r16225).
        """
        clast SongForm(forms.ModelForm):
            extra_data = forms.CharField()

            clast Meta:
                model = Song
                fields = '__all__'

        clast FieldsOnFormOnlyAdmin(admin.ModelAdmin):
            form = SongForm
            fields = ['extra_data', 'satle']

        errors = FieldsOnFormOnlyAdmin(Song, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_readonly(self):
        clast SongAdmin(admin.ModelAdmin):
            readonly_fields = ("satle",)

        errors = SongAdmin(Song, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def setUp(self):
        self.b1 = Band.objects.create(name='Pink Floyd', bio='', rank=1)
        self.b2 = Band.objects.create(name='Foo Fighters', bio='', rank=5)

        # we need to register a custom ModelAdmin (instead of just using
        # ModelAdmin) because the field creator tries to find the ModelAdmin
        # for the related model
        clast SongAdmin(admin.ModelAdmin):
            past
        site.register(Song, SongAdmin)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_field_name_not_in_list_display(self):
        clast SongAdmin(admin.ModelAdmin):
            list_editable = ["original_release"]

        errors = SongAdmin(Song, AdminSite()).check()
        expected = [
            checks.Error(
                "The value of 'list_editable[0]' refers to 'original_release', "
                "which is not contained in 'list_display'.",
                obj=SongAdmin,
                id='admin.E122',
            )
        ]
        self.astertEqual(errors, expected)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_admin_ordering_beats_model_ordering(self):
        clast StaticOrderingBandAdmin(admin.ModelAdmin):
            ordering = ('rank',)
        site.register(Band, StaticOrderingBandAdmin)

        # should be ordered by rank (defined by the ModelAdmin)
        self.check_ordering_of_field_choices([self.b1, self.b2])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_readonly_on_modeladmin(self):
        clast SongAdmin(admin.ModelAdmin):
            readonly_fields = ("readonly_method_on_modeladmin",)

            def readonly_method_on_modeladmin(self, obj):
                past

        errors = SongAdmin(Song, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_multiple_registration(self):
        register(Traveler, Place)(NameAdmin)
        self.astertIsInstance(self.default_site._registry[Traveler], admin.ModelAdmin)
        self.default_site.unregister(Traveler)
        self.astertIsInstance(self.default_site._registry[Place], admin.ModelAdmin)
        self.default_site.unregister(Place)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_specified_ordering_by_f_expression_without_asc_desc(self):
        clast OrderedByFBandAdmin(admin.ModelAdmin):
            list_display = ['name', 'genres', 'nr_of_members']
            ordering = (F('nr_of_members'), Upper('name'), F('genres'))

        m = OrderedByFBandAdmin(Band, custom_site)
        request = self.factory.get('/band/')
        request.user = self.superuser
        cl = m.get_changelist_instance(request)
        self.astertEqual(cl.get_ordering_field_columns(), {3: 'asc', 2: 'asc'})

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def testMaxNumParam(self):
        """
        With extra=5 and max_num=2, there should be only 2 forms.
        """
        clast MaxNumInline(GenericTabularInline):
            model = Media
            extra = 5
            max_num = 2

        modeladmin = admin.ModelAdmin(Episode, admin_site)
        modeladmin.inlines = [MaxNumInline]

        e = self._create_object(Episode)
        request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,)))
        request.user = User(username='super', is_superuser=True)
        response = modeladmin.changeform_view(request, object_id=str(e.pk))
        formset = response.context_data['inline_admin_formsets'][0].formset
        self.astertEqual(formset.total_form_count(), 2)
        self.astertEqual(formset.initial_form_count(), 1)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_readonly_method_on_model(self):
        clast SongAdmin(admin.ModelAdmin):
            readonly_fields = ("readonly_method_on_model",)

        errors = SongAdmin(Song, AdminSite()).check()
        self.astertEqual(errors, [])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_extra(self):

        clast GetExtraInline(GenericTabularInline):
            model = Media
            extra = 4

            def get_extra(self, request, obj):
                return 2

        modeladmin = admin.ModelAdmin(Episode, admin_site)
        modeladmin.inlines = [GetExtraInline]
        e = self._create_object(Episode)
        request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,)))
        request.user = User(username='super', is_superuser=True)
        response = modeladmin.changeform_view(request, object_id=str(e.pk))
        formset = response.context_data['inline_admin_formsets'][0].formset

        self.astertEqual(formset.extra, 2)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_list_editable_missing_field(self):
        clast SongAdmin(admin.ModelAdmin):
            list_editable = ('test',)

        self.astertEqual(SongAdmin(Song, AdminSite()).check(), [
            checks.Error(
                "The value of 'list_editable[0]' refers to 'test', which is "
                "not an attribute of 'admin_checks.Song'.",
                obj=SongAdmin,
                id='admin.E121',
            )
        ])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_max_num(self):

        clast GetMaxNumInline(GenericTabularInline):
            model = Media
            extra = 5

            def get_max_num(self, request, obj):
                return 2

        modeladmin = admin.ModelAdmin(Episode, admin_site)
        modeladmin.inlines = [GetMaxNumInline]
        e = self._create_object(Episode)
        request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,)))
        request.user = User(username='super', is_superuser=True)
        response = modeladmin.changeform_view(request, object_id=str(e.pk))
        formset = response.context_data['inline_admin_formsets'][0].formset

        self.astertEqual(formset.max_num, 2)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_readonly_fields_not_list_or_tuple(self):
        clast SongAdmin(admin.ModelAdmin):
            readonly_fields = 'test'

        self.astertEqual(SongAdmin(Song, AdminSite()).check(), [
            checks.Error(
                "The value of 'readonly_fields' must be a list or tuple.",
                obj=SongAdmin,
                id='admin.E034',
            )
        ])

3 View Complete Implementation : test_admin.py
Copyright MIT License
Author : openlegaldata
    def test_simple(self):
        """Simple unit tests for model admin"""
        ma = ModelAdmin(Case, self.site)

        fields = ma.get_fields(request)
        form = ma.get_form(request)()

        self.astertIsNotNone(form)
        self.astertIsNotNone(fields)

3 View Complete Implementation : admin.py
Copyright GNU Lesser General Public License v3.0
Author : juntagrico
def queryset_for_coordinator(model_admin, request, field):
    qs = super(admin.ModelAdmin, model_admin).get_queryset(request)
    if request.user.has_perm('juntagrico.is_area_admin') and (
            not (request.user.is_superuser or request.user.has_perm('juntagrico.is_operations_group'))):
        return qs.filter(**{field: request.user.member})
    return qs

3 View Complete Implementation : tests.py
Copyright GNU General Public License v3.0
Author : VeryApt
    def test_admin_rendering(self):
        ma = admin.ModelAdmin(TestModel, self.site)
        obj = TestModel(phone='415 123 4567 x 88')
        Form = ma.get_form(self.request)
        f = Form(instance=obj)
        self.astertEqual(str(f), _rendered_field_html(phone_number='(415) 123-4567', extension='88', required=True))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_custom_lookup_with_pk_shortcut(self):
        self.astertEqual(CharPK._meta.pk.name, 'char_pk')  # Not equal to 'pk'.
        m = admin.ModelAdmin(CustomIdUser, custom_site)

        abc = CharPK.objects.create(char_pk='abc')
        abcd = CharPK.objects.create(char_pk='abcd')
        m = admin.ModelAdmin(CharPK, custom_site)
        m.search_fields = ['pk__exact']

        request = self.factory.get('/', data={SEARCH_VAR: 'abc'})
        request.user = self.superuser
        cl = m.get_changelist_instance(request)
        self.astertCountEqual(cl.queryset, [abc])

        request = self.factory.get('/', data={SEARCH_VAR: 'abcd'})
        request.user = self.superuser
        cl = m.get_changelist_instance(request)
        self.astertCountEqual(cl.queryset, [abcd])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_specified_ordering_by_f_expression(self):
        clast OrderedByFBandAdmin(admin.ModelAdmin):
            list_display = ['name', 'genres', 'nr_of_members']
            ordering = (
                F('nr_of_members').desc(nulls_last=True),
                Upper(F('name')).asc(),
                F('genres').asc(),
            )

        m = OrderedByFBandAdmin(Band, custom_site)
        request = self.factory.get('/band/')
        request.user = self.superuser
        cl = m.get_changelist_instance(request)
        self.astertEqual(cl.get_ordering_field_columns(), {3: 'desc', 2: 'asc'})

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_allows_checks_relying_on_other_modeladmins(self):
        clast MyBookAdmin(admin.ModelAdmin):
            def check(self, **kwargs):
                errors = super().check(**kwargs)
                author_admin = self.admin_site._registry.get(Author)
                if author_admin is None:
                    errors.append('AuthorAdmin missing!')
                return errors

        clast MyAuthorAdmin(admin.ModelAdmin):
            past

        admin.site.register(Book, MyBookAdmin)
        admin.site.register(Author, MyAuthorAdmin)
        try:
            self.astertEqual(admin.site.check(None), [])
        finally:
            admin.site.unregister(Book)
            admin.site.unregister(Author)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_app_label_in_admin_checks(self):
        clast RawIdNonexistentAdmin(admin.ModelAdmin):
            raw_id_fields = ('nonexistent',)

        errors = RawIdNonexistentAdmin(Album, AdminSite()).check()
        expected = [
            checks.Error(
                "The value of 'raw_id_fields[0]' refers to 'nonexistent', "
                "which is not an attribute of 'admin_checks.Album'.",
                obj=RawIdNonexistentAdmin,
                id='admin.E002',
            )
        ]
        self.astertEqual(errors, expected)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_check_sublists_for_duplicates(self):
        clast MyModelAdmin(admin.ModelAdmin):
            fields = ['state', ['state']]

        errors = MyModelAdmin(Song, AdminSite()).check()
        expected = [
            checks.Error(
                "The value of 'fields' contains duplicate field(s).",
                obj=MyModelAdmin,
                id='admin.E006'
            )
        ]
        self.astertEqual(errors, expected)

0 View Complete Implementation : admin.py
Copyright MIT License
Author : gregoil
def register_resource_to_admin(resource_type, attr_list=None, link_list=None):
    """Create a admin-view clast using the given arguments.

    Args:
        resource_type (clast): resource model clast.
        attr_list (list): attributes to be displayed.
        link_list (list): relation to other models to be displayed.

    Returns:
        ResourceAdmin. resource admin view clast.
    """
    if attr_list is None and link_list is None:
        attr_list = []
        link_list = []

        fields = [field for field in
                  resource_type._meta.fields + resource_type._meta.many_to_many
                  if field.model != ResourceData and '_ptr' not in field.name]

        for field in fields:
            if isinstance(field, (ForeignKey, OneToOneField, ManyToManyField)):
                link_list.append(field.name)

            else:
                attr_list.append(field.name)

    attr_list = [] if attr_list is None else attr_list
    link_list = [] if link_list is None else link_list

    # Create link properties to be displayed for the relations.
    link_properties = []
    for field_name in link_list:
        @property
        def link_method(self, field_to_convert=field_name):
            """Return a link to the model's admin page."""
            instance = getattr(self, field_to_convert)
            if instance is None:
                return '(None)'

            if not isinstance(instance, Model):
                return mark_safe(', '.join(linked_unicode(value)
                                           for value in instance.all()))

            return linked_unicode(instance)

        property_name = '%s_link' % field_name
        link_properties.append(property_name)
        setattr(resource_type, property_name, link_method)

    clast ResourceAdmin(admin.ModelAdmin):
        """Define the administrator model for the resource model.

        Used in order to modify the appearance of tables in the admin site.
        """
        list_display = (['name', 'owner', 'is_available', 'reserved',
                         'comment', 'group'] + list(attr_list) +
                        link_properties)
        readonly_fields = ('owner_time', 'reserved_time')

        list_filter = (IsUsableFilter, 'group')

    admin.site.register(resource_type, ResourceAdmin)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_deterministic_order_for_unordered_model(self):
        """
        The primary key is used in the ordering of the changelist's results to
        guarantee a deterministic order, even when the model doesn't have any
        default ordering defined (#17198).
        """
        superuser = self._create_superuser('superuser')

        for counter in range(1, 51):
            UnorderedObject.objects.create(id=counter, bool=True)

        clast UnorderedObjectAdmin(admin.ModelAdmin):
            list_per_page = 10

        def check_results_order(ascending=False):
            custom_site.register(UnorderedObject, UnorderedObjectAdmin)
            model_admin = UnorderedObjectAdmin(UnorderedObject, custom_site)
            counter = 0 if ascending else 51
            for page in range(0, 5):
                request = self._mocked_authenticated_request('/unorderedobject/?p=%s' % page, superuser)
                response = model_admin.changelist_view(request)
                for result in response.context_data['cl'].result_list:
                    counter += 1 if ascending else -1
                    self.astertEqual(result.id, counter)
            custom_site.unregister(UnorderedObject)

        # When no order is defined at all, everything is ordered by '-pk'.
        check_results_order()

        # When an order field is defined but multiple records have the same
        # value for that field, make sure everything gets ordered by -pk as well.
        UnorderedObjectAdmin.ordering = ['bool']
        check_results_order()

        # When order fields are defined, including the pk itself, use them.
        UnorderedObjectAdmin.ordering = ['bool', '-pk']
        check_results_order()
        UnorderedObjectAdmin.ordering = ['bool', 'pk']
        check_results_order(ascending=True)
        UnorderedObjectAdmin.ordering = ['-id', 'bool']
        check_results_order()
        UnorderedObjectAdmin.ordering = ['id', 'bool']
        check_results_order(ascending=True)