Python django.contrib.admin.ModelAdmin() Examples
The following are 30 code examples for showing how to use django.contrib.admin.ModelAdmin(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
You may check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
django.contrib.admin
, or try the search function
.
Example 1
Project: django-admin-view-permission Author: ctxis File: admin.py License: BSD 2-Clause "Simplified" License | 6 votes |
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 2
Project: lexpredict-contraxsuite Author: LexPredict File: admin.py License: GNU Affero General Public License v3.0 | 6 votes |
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 3
Project: django-ca Author: mathiasertl File: admin.py License: GNU General Public License v3.0 | 6 votes |
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 4
Project: django-collaborative Author: propublica File: admin.py License: MIT License | 6 votes |
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 5
Project: ChRIS_ultron_backEnd Author: FNNDSC File: admin.py License: MIT License | 6 votes |
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
Project: djongo Author: nesdis File: tests.py License: GNU Affero General Public License v3.0 | 6 votes |
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 7
Project: djongo Author: nesdis File: tests.py License: GNU Affero General Public License v3.0 | 6 votes |
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 8
Project: djongo Author: nesdis File: tests.py License: GNU Affero General Public License v3.0 | 6 votes |
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 9
Project: djongo Author: nesdis File: tests.py License: GNU Affero General Public License v3.0 | 6 votes |
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 10
Project: djongo Author: nesdis File: tests.py License: GNU Affero General Public License v3.0 | 6 votes |
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 11
Project: djongo Author: nesdis File: tests.py License: GNU Affero General Public License v3.0 | 6 votes |
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 12
Project: djongo Author: nesdis File: tests.py License: GNU Affero General Public License v3.0 | 6 votes |
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 13
Project: djongo Author: nesdis File: tests.py License: GNU Affero General Public License v3.0 | 6 votes |
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 14
Project: djongo Author: nesdis File: tests.py License: GNU Affero General Public License v3.0 | 6 votes |
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 15
Project: djongo Author: nesdis File: tests.py License: GNU Affero General Public License v3.0 | 6 votes |
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
Project: djongo Author: nesdis File: tests.py License: GNU Affero General Public License v3.0 | 6 votes |
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
Project: djreservation Author: luisza File: admin.py License: GNU General Public License v3.0 | 5 votes |
def get_readonly_fields(self, request, obj=None): readonly = admin.ModelAdmin.get_readonly_fields(self, request, obj=obj) if obj and obj.status == obj.RETURNED: readonly= ("user", "status", "updated_datetime", "reserved_start_date", "reserved_end_date", "list_of_products") return readonly
Example 18
Project: djreservation Author: luisza File: admin.py License: GNU General Public License v3.0 | 5 votes |
def get_queryset(self, request): queryset = admin.ModelAdmin.get_queryset(self, request) queryset = queryset.exclude(status=Reservation.BUILDING) return queryset
Example 19
Project: djreservation Author: luisza File: admin.py License: GNU General Public License v3.0 | 5 votes |
def save_model(self, request, obj, form, change): differ_obj = [] old_status, product_change = -1, False if change: old_status = obj.__class__.objects.filter( pk=obj.pk).values_list('status')[0][0] dev = admin.ModelAdmin.save_model(self, request, obj, form, change) if 'djreservation_product_list' in request.POST: product_pks = request.POST.getlist("djreservation_product_list") old_pks = list(map(lambda x: str(x[0]), obj.product_set.all().filter( borrowed=True).values_list("pk"))) differ_obj = different(product_pks, old_pks) if any(differ_obj): obj.product_set.all().exclude( pk__in=product_pks).update(borrowed=False) obj.product_set.all().filter( pk__in=product_pks).update(borrowed=True) product_change = True change_status = int(old_status) != obj.status if product_change or change_status: # send_reservation_email(obj, request.user) proccess_reservation(obj, differ_obj, change_status) return dev
Example 20
Project: GTDWeb Author: lanbing510 File: decorators.py License: GNU General Public License v2.0 | 5 votes |
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): 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 21
Project: GTDWeb Author: lanbing510 File: options.py License: GNU General Public License v2.0 | 5 votes |
def formfield_for_dbfield(self, db_field, **kwargs): """ Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing 2D GeometryFields (OpenLayers 2 does not support 3D editing). """ if isinstance(db_field, models.GeometryField) and db_field.dim < 3: kwargs.pop('request', None) # Setting the widget with the newly defined widget. kwargs['widget'] = self.get_map_widget(db_field) return db_field.formfield(**kwargs) else: return super(GeoModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)
Example 22
Project: yata Author: Kivou-2000607 File: admin.py License: GNU General Public License v3.0 | 5 votes |
def last_action(self, instance): return timestampToDate(instance.lastActionTS) # class NewsAdmin(admin.ModelAdmin): # list_display = ['__str__', 'date', 'type', 'authorName', 'authorId', 'read'] # filter_horizontal = ('player',)
Example 23
Project: django-admin-view-permission Author: ctxis File: admin.py License: BSD 2-Clause "Simplified" License | 5 votes |
def register(self, model_or_iterable, admin_class=None, **options): """ Create a new ModelAdmin class which inherits from the original and the above and register all models with that """ SETTINGS_MODELS = getattr( settings, 'ADMIN_VIEW_PERMISSION_MODELS', None) models = model_or_iterable if not isinstance(model_or_iterable, (tuple, list)): models = tuple([model_or_iterable]) is_user_model = settings.AUTH_USER_MODEL in [ get_model_name(i) for i in models] if SETTINGS_MODELS or (SETTINGS_MODELS is not None and len( SETTINGS_MODELS) == 0): for model in models: model_name = get_model_name(model) if model_name in SETTINGS_MODELS: admin_class = self._get_admin_class( admin_class, is_user_model) super(AdminViewPermissionAdminSite, self).register( [model], admin_class, **options) else: admin_class = self._get_admin_class(admin_class, is_user_model) super(AdminViewPermissionAdminSite, self).register( model_or_iterable, admin_class, **options)
Example 24
Project: django-admin-view-permission Author: ctxis File: test_others.py License: BSD 2-Clause "Simplified" License | 5 votes |
def test_testapp_modeladmin_override(self): for model in admin.site._registry: assert isinstance( admin.site._registry[model], AdminViewPermissionModelAdmin) assert isinstance( admin.site._registry[model], admin.ModelAdmin)
Example 25
Project: django-admin-view-permission Author: ctxis File: test_admin.py License: BSD 2-Clause "Simplified" License | 5 votes |
def test_register__2(self): modeladmin1 = type(str('TestModelAdmin1'), (admin.ModelAdmin, ), {}) self.admin_site.register(TestModel1, modeladmin1) assert isinstance(self.admin_site._registry[TestModel1], AdminViewPermissionModelAdmin) assert isinstance(self.admin_site._registry[TestModel1], modeladmin1)
Example 26
Project: django-admin-view-permission Author: ctxis File: test_admin.py License: BSD 2-Clause "Simplified" License | 5 votes |
def test_register__4(self): modeladmin1 = type(str('TestModelAdmin1'), (admin.ModelAdmin, ), {}) self.admin_site.register(TestModel1, modeladmin1) assert isinstance(self.admin_site._registry[TestModel1], AdminViewPermissionModelAdmin) assert isinstance(self.admin_site._registry[TestModel1], modeladmin1)
Example 27
Project: bioforum Author: reBiocoder File: decorators.py License: MIT License | 5 votes |
def register(*models, site=None): """ Register the given model(s) classes and wrapped ModelAdmin class with admin site: @register(Author) class AuthorAdmin(admin.ModelAdmin): pass The `site` kwarg is an admin site to use instead of the default admin site. """ from django.contrib.admin import ModelAdmin from django.contrib.admin.sites import site as default_site, AdminSite def _model_admin_wrapper(admin_class): if not models: raise ValueError('At least one model must be passed to register.') admin_site = site or default_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 28
Project: bioforum Author: reBiocoder File: sites.py License: MIT License | 5 votes |
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 29
Project: bioforum Author: reBiocoder File: options.py License: MIT License | 5 votes |
def formfield_for_dbfield(self, db_field, request, **kwargs): """ Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing 2D GeometryFields (OpenLayers 2 does not support 3D editing). """ if isinstance(db_field, models.GeometryField) and db_field.dim < 3: # Setting the widget with the newly defined widget. kwargs['widget'] = self.get_map_widget(db_field) return db_field.formfield(**kwargs) else: return super().formfield_for_dbfield(db_field, request, **kwargs)
Example 30
Project: django-seo Author: whyflyru File: admin.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_path_admin(use_site=False, use_subdomains=False): list_display = ['_path'] search_fields = ['_path'] list_filter = [] if use_site: list_display.append('_site') list_filter.append('_site') if use_subdomains: list_display.append('_subdomain') return type('PathMetadataAdmin', (admin.ModelAdmin, ), { 'list_display': tuple(list_display), 'list_filter': tuple(list_filter), 'search_fields': tuple(search_fields) })