Python django.contrib.admin.ModelAdmin() Examples

The following are 30 code examples of django.contrib.admin.ModelAdmin(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.admin , or try the search function .
Example #1
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 8 votes vote down vote up
def test_exclude_inline_model_admin(self):
        """
        Regression test for #9932 - exclude in InlineModelAdmin should not
        contain the ForeignKey field used in ModelAdmin.model
        """
        class SongInline(admin.StackedInline):
            model = Song
            exclude = ['album']

        class AlbumAdmin(admin.ModelAdmin):
            model = Album
            inlines = [SongInline]

        errors = AlbumAdmin(Album, AdminSite()).check()
        expected = [
            checks.Error(
                "Cannot exclude the field 'album', because it is the foreign key "
                "to the parent model 'admin_checks.Album'.",
                obj=SongInline,
                id='admin.E201',
            )
        ]
        self.assertEqual(errors, expected) 
Example #2
Source File: admin.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def csr_details_view(self, request):
        """Returns details of a CSR request."""

        if not request.user.is_staff or not self.has_change_permission(request):
            # NOTE: is_staff is already assured by ModelAdmin, but just to be sure
            raise PermissionDenied

        try:
            csr = x509.load_pem_x509_csr(force_bytes(request.POST['csr']), default_backend())
        except Exception as e:
            return HttpResponseBadRequest(json.dumps({
                'message': str(e),
            }), content_type='application/json')

        subject = {OID_NAME_MAPPINGS[s.oid]: s.value for s in csr.subject}
        return HttpResponse(json.dumps({
            'subject': subject,
        }), content_type='application/json') 
Example #3
Source File: admin.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_queryset(self, request):
        self.last_request = request
        # qs = admin.ModelAdmin.get_queryset(self, request)
        qs = TermUsage.objects.all()
        if 'q' in request.GET:
            # searching by count?
            request.GET = request.GET.copy()
            query_text = request.GET.pop('q')
            query_text = query_text[0] if query_text else ''
            if query_text:
                queries = Q(term__term__icontains=query_text) | \
                          Q(document__name__icontains=query_text) | \
                          Q(document__project__name__icontains=query_text)
                if query_text.isdigit():
                    queries |= (Q(count__gt=int(query_text) - 1))
                qs = qs.filter(queries)
        qs = qs.only('id', 'text_unit_id', 'count', 'term')
        qs = self.filter_count_predicate(qs)
        return qs 
Example #4
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_allows_checks_relying_on_other_modeladmins(self):
        class 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

        class MyAuthorAdmin(admin.ModelAdmin):
            pass

        admin.site.register(Book, MyBookAdmin)
        admin.site.register(Author, MyAuthorAdmin)
        try:
            self.assertEqual(admin.site.check(None), [])
        finally:
            admin.site.unregister(Book)
            admin.site.unregister(Author) 
Example #5
Source File: admin.py    From ChRIS_ultron_backEnd with MIT License 6 votes vote down vote up
def change_view(self, request, object_id, form_url='', extra_context=None):
        """
        Overriden to show all plugin's fields in the view plugin page.
        """
        self.readonly_fields = [fl for fl in plugin_readonly_fields]
        self.readonly_fields.append('get_registered_compute_resources')
        self.fieldsets = [
            ('Compute resources', {'fields': ['compute_resources',
                                              'get_registered_compute_resources']}),
            ('Plugin properties', {'fields': plugin_readonly_fields}),
        ]
        return admin.ModelAdmin.change_view(self, request, object_id, form_url,
                                            extra_context)

    # def save_model(self, request, obj, form, change):
    #     """
    #     Overriden to set the modification date..
    #     """
    #     if change:
    #         obj.modification_date = timezone.now()
    #     super().save_model(request, obj, form, change) 
Example #6
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_fieldsets_fields_non_tuple(self):
        """
        The first fieldset's fields must be a list/tuple.
        """
        class NotATupleAdmin(admin.ModelAdmin):
            list_display = ["pk", "title"]
            list_editable = ["title"]
            fieldsets = [
                (None, {
                    "fields": "title"  # not a tuple
                }),
            ]

        errors = NotATupleAdmin(Song, AdminSite()).check()
        expected = [
            checks.Error(
                "The value of 'fieldsets[0][1]['fields']' must be a list or tuple.",
                obj=NotATupleAdmin,
                id='admin.E008',
            )
        ]
        self.assertEqual(errors, expected) 
Example #7
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_nonfirst_fieldset(self):
        """
        The second fieldset's fields must be a list/tuple.
        """
        class NotATupleAdmin(admin.ModelAdmin):
            fieldsets = [
                (None, {
                    "fields": ("title",)
                }),
                ('foo', {
                    "fields": "author"  # not a tuple
                }),
            ]

        errors = NotATupleAdmin(Song, AdminSite()).check()
        expected = [
            checks.Error(
                "The value of 'fieldsets[1][1]['fields']' must be a list or tuple.",
                obj=NotATupleAdmin,
                id='admin.E008',
            )
        ]
        self.assertEqual(errors, expected) 
Example #8
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_exclude_values(self):
        """
        Tests for basic system checks of 'exclude' option values (#12689)
        """
        class 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.assertEqual(errors, expected) 
Example #9
Source File: admin.py    From django-collaborative with MIT License 6 votes vote down vote up
def attempt_register(self, Model, ModelAdmin):
        try:
            admin.site.unregister(Model)
        except admin.sites.NotRegistered:
            pass
        try:
            admin.site.register(Model, ModelAdmin)
        except admin.sites.AlreadyRegistered:
            logger.warning("WARNING! %s admin already exists." % (
                str(Model)
            ))

        # If we don't do this, our module will show up in admin but
        # it will show up as an unclickable thing with on add/change
        importlib.reload(import_module(settings.ROOT_URLCONF))
        clear_url_caches() 
Example #10
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_generic_inline_model_admin_non_generic_model(self):
        """
        A model without a GenericForeignKey raises problems if it's included
        in a GenericInlineModelAdmin definition.
        """
        class BookInline(GenericStackedInline):
            model = Book

        class SongAdmin(admin.ModelAdmin):
            inlines = [BookInline]

        errors = SongAdmin(Song, AdminSite()).check()
        expected = [
            checks.Error(
                "'admin_checks.Book' has no GenericForeignKey.",
                obj=BookInline,
                id='admin.E301',
            )
        ]
        self.assertEqual(errors, expected) 
Example #11
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_generic_inline_model_admin_non_gfk_ct_field(self):
        """
        A GenericInlineModelAdmin raises problems if the ct_field points to a
        field that isn't part of a GenericForeignKey.
        """
        class InfluenceInline(GenericStackedInline):
            model = Influence
            ct_field = 'name'

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

        errors = SongAdmin(Song, AdminSite()).check()
        expected = [
            checks.Error(
                "'admin_checks.Influence' has no GenericForeignKey using "
                "content type field 'name' and object ID field 'object_id'.",
                obj=InfluenceInline,
                id='admin.E304',
            )
        ]
        self.assertEqual(errors, expected) 
Example #12
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_generic_inline_model_admin_non_gfk_fk_field(self):
        """
        A GenericInlineModelAdmin raises problems if the ct_fk_field points to
        a field that isn't part of a GenericForeignKey.
        """
        class InfluenceInline(GenericStackedInline):
            model = Influence
            ct_fk_field = 'name'

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

        errors = SongAdmin(Song, AdminSite()).check()
        expected = [
            checks.Error(
                "'admin_checks.Influence' has no GenericForeignKey using "
                "content type field 'content_type' and object ID field 'name'.",
                obj=InfluenceInline,
                id='admin.E304',
            )
        ]
        self.assertEqual(errors, expected) 
Example #13
Source File: admin.py    From django-admin-view-permission with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_excluded_fields(self):
        """
        Check if we have no excluded fields defined as we never want to
        show those (to any user)
        """
        if self.exclude is None:
            exclude = []
        else:
            exclude = list(self.exclude)

        # logic taken from: django.contrib.admin.options.ModelAdmin#get_form
        if self.exclude is None and hasattr(
                self.form, '_meta') and self.form._meta.exclude:
            # Take the custom ModelForm's Meta.exclude into account only
            # if the ModelAdmin doesn't define its own.
            exclude.extend(self.form._meta.exclude)

        return exclude 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_generic_inline_model_admin_bad_ct_field(self):
        """
        A GenericInlineModelAdmin errors if the ct_field points to a
        nonexistent field.
        """
        class InfluenceInline(GenericStackedInline):
            model = Influence
            ct_field = 'nonexistent'

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

        errors = SongAdmin(Song, AdminSite()).check()
        expected = [
            checks.Error(
                "'ct_field' references 'nonexistent', which is not a field on 'admin_checks.Influence'.",
                obj=InfluenceInline,
                id='admin.E302',
            )
        ]
        self.assertEqual(errors, expected) 
Example #15
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_fk_exclusion(self):
        """
        Regression test for #11709 - when testing for fk excluding (when exclude is
        given) make sure fk_name is honored or things blow up when there is more
        than one fk to the parent model.
        """
        class TwoAlbumFKAndAnEInline(admin.TabularInline):
            model = TwoAlbumFKAndAnE
            exclude = ("e",)
            fk_name = "album1"

        class MyAdmin(admin.ModelAdmin):
            inlines = [TwoAlbumFKAndAnEInline]

        errors = MyAdmin(Album, AdminSite()).check()
        self.assertEqual(errors, []) 
Example #16
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_inline_self_check(self):
        class TwoAlbumFKAndAnEInline(admin.TabularInline):
            model = TwoAlbumFKAndAnE

        class MyAdmin(admin.ModelAdmin):
            inlines = [TwoAlbumFKAndAnEInline]

        errors = MyAdmin(Album, AdminSite()).check()
        expected = [
            checks.Error(
                "'admin_checks.TwoAlbumFKAndAnE' has more than one ForeignKey to 'admin_checks.Album'.",
                obj=TwoAlbumFKAndAnEInline,
                id='admin.E202',
            )
        ]
        self.assertEqual(errors, expected) 
Example #17
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_readonly(self):
        class SongAdmin(admin.ModelAdmin):
            readonly_fields = ("title",)

        errors = SongAdmin(Song, AdminSite()).check()
        self.assertEqual(errors, []) 
Example #18
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_app_label_in_admin_checks(self):
        class 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.assertEqual(errors, expected) 
Example #19
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_valid_generic_inline_model_admin(self):
        """
        Regression test for #22034 - check that generic inlines don't look for
        normal ForeignKey relations.
        """
        class InfluenceInline(GenericStackedInline):
            model = Influence

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

        errors = SongAdmin(Song, AdminSite()).check()
        self.assertEqual(errors, []) 
Example #20
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_list_editable_missing_field(self):
        class SongAdmin(admin.ModelAdmin):
            list_editable = ('test',)

        self.assertEqual(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',
            )
        ]) 
Example #21
Source File: admin.py    From ecommerce_website_development with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def delete_model(self, request, obj):
        """删除数据时调用"""
        # 调用ModelAdmin中delete_model来实现删除操作
        super().delete_model(request, obj)

        # 附加操作:发出生成静态首页的任务
        from celery_tasks.tasks import generate_static_index_html
        generate_static_index_html.delay()

        # 附加操作: 清除首页缓存
        cache.delete('index_page_data') 
Example #22
Source File: admin.py    From ecommerce_website_development with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def save_model(self, request, obj, form, change):
        """新增或更新时调用"""
        # 调用ModelAdmin中save_model来实现更新或新增
        super().save_model(request, obj, form, change)

        # 附加操作:发出生成静态首页的任务
        from celery_tasks.tasks import generate_static_index_html
        print('发出重新生成静态首页的任务')
        generate_static_index_html.delay()

        # 附加操作: 清除首页缓存
        cache.delete('index_page_data') 
Example #23
Source File: admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def profiles_view(self, request):
        """Returns profiles."""

        if not request.user.is_staff or not self.has_change_permission(request):
            # NOTE: is_staff is already assured by ModelAdmin, but just to be sure
            raise PermissionDenied

        data = {name: profiles[name].serialize() for name in ca_settings.CA_PROFILES}
        return HttpResponse(json.dumps(data, cls=LazyEncoder), content_type='application/json') 
Example #24
Source File: decorators.py    From python2017 with MIT License 5 votes vote down vote up
def register(*models, **kwargs):
    """
    Registers the given model(s) classes and wrapped ModelAdmin class with
    admin site:

    @register(Author)
    class AuthorAdmin(admin.ModelAdmin):
        pass

    A kwarg of `site` can be passed as the admin site, otherwise the default
    admin site will be used.
    """
    from django.contrib.admin import ModelAdmin
    from django.contrib.admin.sites import site, AdminSite

    def _model_admin_wrapper(admin_class):
        if not models:
            raise ValueError('At least one model must be passed to register.')

        admin_site = kwargs.pop('site', site)

        if not isinstance(admin_site, AdminSite):
            raise ValueError('site must subclass AdminSite')

        if not issubclass(admin_class, ModelAdmin):
            raise ValueError('Wrapped class must subclass ModelAdmin.')

        admin_site.register(models, admin_class=admin_class)

        return admin_class
    return _model_admin_wrapper 
Example #25
Source File: admin.py    From ChRIS_ultron_backEnd with MIT License 5 votes vote down vote up
def add_view(self, request, form_url='', extra_context=None):
        """
        Overriden to only show the required fields in the add plugin page.
        """
        self.readonly_fields = []
        self.fieldsets = [
            ('Compute resources', {'fields': ['compute_resources']}),
            ('Identify plugin by name and version', {'fields': [('name', 'version')]}),
            ('Or identify plugin by url', {'fields': ['url']}),
        ]
        return admin.ModelAdmin.add_view(self, request, form_url, extra_context) 
Example #26
Source File: admin.py    From ChRIS_ultron_backEnd with MIT License 5 votes vote down vote up
def change_view(self, request, object_id, form_url='', extra_context=None):
        """
        Overriden to show all compute resources's fields in the compute resource page.
        """
        self.fields = ['name', 'description', 'creation_date', 'modification_date']
        return admin.ModelAdmin.change_view(self, request, object_id, form_url,
                                            extra_context) 
Example #27
Source File: admin.py    From ChRIS_ultron_backEnd with MIT License 5 votes vote down vote up
def add_view(self, request, form_url='', extra_context=None):
        """
        Overriden to only show the required fields in the add compute resource page.
        """
        self.fields = ['name', 'description']
        return admin.ModelAdmin.add_view(self, request, form_url, extra_context) 
Example #28
Source File: admin.py    From django-collaborative with MIT License 5 votes vote down vote up
def register(self):
        try:
            create_models()
        except Exception:
            pass
        for Model in apps.get_models():
            if not self.should_register_admin(Model):
                continue

            ModelAdmin = self.create_admin(Model)
            self.attempt_register(Model, ModelAdmin) 
Example #29
Source File: sites.py    From python2017 with MIT License 5 votes vote down vote up
def check(self, app_configs):
        """
        Run the system checks on all ModelAdmins, except if they aren't
        customized at all.
        """
        if app_configs is None:
            app_configs = apps.get_app_configs()
        app_configs = set(app_configs)  # Speed up lookups below

        errors = []
        modeladmins = (o for o in self._registry.values() if o.__class__ is not ModelAdmin)
        for modeladmin in modeladmins:
            if modeladmin.model._meta.app_config in app_configs:
                errors.extend(modeladmin.check())
        return errors 
Example #30
Source File: admin.py    From django-collaborative with MIT License 5 votes vote down vote up
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_class": resource,
            # "fields": fields,
            # "readonly_fields": ro_fields,
        })