我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.admin.ModelAdmin()。
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: if not HAS_GDAL and db_field.srid != self.map_srid: raise ImproperlyConfigured( "Map SRID is %s and SRID of `%s` is %s. GDAL must be " "installed to perform the transformation." % (self.map_srid, db_field, db_field.srid) ) # 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, request, **kwargs)
def lookups(self, request, model_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. :param request: Http Request instance :type request: django.http.HttpRequest :param model_admin: Django modeladmin instance :type model_admin: django.contrib.admin.ModelAdmin :return: List of tuples """ content_type_ids = model_admin.model.objects.values_list( 'content_type', flat=True ).distinct() return list(map( lambda x: (x.pk, x.name), ContentType.objects.filter(pk__in=content_type_ids) ))
def __new__(cls, clsname, bases, attrs): # making sure we are using the correct class if len(bases) < 1: # pragma: no cover raise ValueError('SettingsBaseAdminForm requires a base class') # django ModelAdmin classes are required to have a Meta member class # with a 'model' attribute that points to the model type meta = type('SettingsBaseAdminModelAdminMeta', (object, ), {'model': bases[0]}) class_dict = {'Meta': meta} # we want all our generic form behaviours to be inherited as well, so # add these to the attribute dict. class_dict['form'] = _SettingsBaseGenericModelFormMeta( clsname, bases, attrs) class_dict.update(attrs) model_admin = type( bases[0].__name__ + 'ModelAdmin', (_SettingsBaseModelAdminTemplate, ), class_dict) return model_admin
def formfield_for_foreignkey(self, db_field, request=None, **kwargs): """ Replicates the logic in ModelAdmin.forfield_for_foreignkey, replacing the widget with the patched one above, initialising it with the child admin site. """ db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = PolymorphicForeignKeyRawIdWidget( db_field.rel, admin_site=self._get_child_admin_site(db_field.rel), using=db ) if 'queryset' not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs['queryset'] = queryset return db_field.formfield(**kwargs) return super(PolymorphicAdminRawIdFix, self).formfield_for_foreignkey( db_field, request=request, **kwargs)
def formfield_for_manytomany(self, db_field, request=None, **kwargs): """ Replicates the logic in ModelAdmin.formfield_for_manytomany, replacing the widget with the patched one above, initialising it with the child admin site. """ db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = PolymorphicManyToManyRawIdWidget( db_field.rel, admin_site=self._get_child_admin_site(db_field.rel), using=db ) kwargs['help_text'] = '' if 'queryset' not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs['queryset'] = queryset return db_field.formfield(**kwargs) return super(PolymorphicAdminRawIdFix, self).formfield_for_manytomany( db_field, request=request, **kwargs)
def changelist_view(self, request, extra_context=None): """ Redirect to the ``Page`` changelist view for ``Page`` subclasses. """ # If this is a popup, then return the admin.ModelAdmin changelist view if IS_POPUP_VAR in request.GET: opts = self.model._meta app_label = opts.app_label self.change_list_template = [ 'admin/%s/%s/change_list.html' % (app_label, opts.model_name), 'admin/%s/change_list.html' % app_label, 'admin/change_list.html' ] return admin.ModelAdmin.changelist_view(self,request,extra_context) return super(PageAdmin, self).changelist_view(request, extra_context)
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
def _get_post_url(self, obj): """ Needed to retrieve the changelist url as Folder/File can be extended and admin url may change """ # Code from django ModelAdmin to determine changelist on the fly opts = obj._meta if LTE_DJANGO_1_7: model_name = opts.module_name else: model_name = opts.model_name return reverse('admin:%s_%s_changelist' % (opts.app_label, model_name), current_app=self.admin_site.name)
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)
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
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
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(GeoModelAdmin, self).formfield_for_dbfield(db_field, request, **kwargs)
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
def test_extends_model_admin(self): """ The class should extend ModelAdmin """ self.assertTrue(issubclass(CsvExportAdmin, ModelAdmin))
def response_add(self, request, obj, post_url_continue=None): ''' This just modifies the normal ModelAdmin process in order to pass capacity and room options for the added Location along with the location's name and ID. ''' IS_POPUP_VAR = '_popup' TO_FIELD_VAR = '_to_field' if IS_POPUP_VAR in request.POST: to_field = request.POST.get(TO_FIELD_VAR) if to_field: attr = str(to_field) else: attr = obj._meta.pk.attname value = obj.serializable_value(attr) popup_response_data = json.dumps({ 'value': six.text_type(value), 'obj': six.text_type(obj), # Add this extra data 'defaultCapacity': obj.defaultCapacity, 'roomOptions': json.dumps([{'id': x.id, 'name': x.name, 'defaultCapacity': x.defaultCapacity} for x in obj.room_set.all()]), }) # Return a modified template return SimpleTemplateResponse('core/admin/location_popup_response.html', { 'popup_response_data': popup_response_data, }) # Otherwise just use the standard ModelAdmin method return super(LocationAdmin,self).response_add(request, obj, post_url_continue)
def response_change(self, request, obj): ''' This just modifies the normal ModelAdmin process in order to pass capacity and room options for the modified Location along with the location's name and ID. ''' IS_POPUP_VAR = '_popup' TO_FIELD_VAR = '_to_field' if IS_POPUP_VAR in request.POST: to_field = request.POST.get(TO_FIELD_VAR) attr = str(to_field) if to_field else obj._meta.pk.attname # Retrieve the `object_id` from the resolved pattern arguments. value = request.resolver_match.args[0] new_value = obj.serializable_value(attr) popup_response_data = json.dumps({ 'action': 'change', 'value': six.text_type(value), 'obj': six.text_type(obj), 'new_value': six.text_type(new_value), # Add this extra data 'defaultCapacity': obj.defaultCapacity, 'roomOptions': json.dumps([{'id': x.id, 'name': x.name, 'defaultCapacity': x.defaultCapacity} for x in obj.room_set.all()]), }) # Return a modified template return SimpleTemplateResponse('core/admin/location_popup_response.html', { 'popup_response_data': popup_response_data, }) return super(LocationAdmin,self).response_change(request, obj)
def get_search_results(self, request, queryset, search_term): # HACK: Bypass UrlNodeParentAdmin's get_search_results, which limits # results to top-level pages so as to avoid breaking the mptt code in # the list view. Our list view is much simpler, so we don't need to # skip it. if isinstance(self, UrlNodeParentAdmin): return super(UrlNodeParentAdmin, self).get_search_results( request, queryset, search_term) # return admin.ModelAdmin.get_search_results( # self, request, queryset, search_term) else: return super(ICEkitFluentPagesParentAdmin, self).get_search_results( request, queryset, search_term)
def get_actions(self, request): """ Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action. """ # If self.actions is explicitly set to None that means that we don't # want *any* actions enabled on this page. if self.actions is None or IS_POPUP_VAR in request.GET: return OrderedDict() actions = [] # Gather actions from the admin site first for (name, func) in self.admin_site.actions: description = getattr(func, 'short_description', name.replace('_', ' ')) actions.append((func, name, description)) # get_action might have returned None, so filter any of those out. actions = filter(None, actions) # Convert the actions into an OrderedDict keyed by name. actions = OrderedDict( (name, (func, name, desc)) for func, name, desc in actions ) return actions
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
def get_queryset(self, request): queryset = admin.ModelAdmin.get_queryset(self, request) queryset = queryset.exclude(status=Reservation.BUILDING) return queryset
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
def register_resource_to_admin(resource_type, attr_list=(), link_list=()): """Create a admin-view class using the given arguments. Args: resource_type (class): resource model class. attr_list (list): attributes to be displayed. link_list (list): relation to other models to be displayed. Returns: ResourceAdmin. resource admin view class. """ # 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)' return linked_unicode(instance) property_name = '%s_link' % field_name link_properties.append(property_name) setattr(resource_type, property_name, link_method) class 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)
def register_child(self, model, model_admin): """ Register a model with admin to display. """ # After the get_urls() is called, the URLs of the child model can't be exposed anymore to the Django URLconf, # which also means that a "Save and continue editing" button won't work. if self._is_setup: raise RegistrationClosed("The admin model can't be registered anymore at this point.") if not issubclass(model, self.base_model): raise TypeError("{0} should be a subclass of {1}".format(model.__name__, self.base_model.__name__)) if not issubclass(model_admin, admin.ModelAdmin): raise TypeError("{0} should be a subclass of {1}".format(model_admin.__name__, admin.ModelAdmin.__name__)) self._child_admin_site.register(model, model_admin)
def get_form(self, request, obj=None, **kwargs): # The django admin validation requires the form to have a 'class Meta: model = ..' # attribute, or it will complain that the fields are missing. # However, this enforces all derived ModelAdmin classes to redefine the model as well, # because they need to explicitly set the model again - it will stick with the base model. # # Instead, pass the form unchecked here, because the standard ModelForm will just work. # If the derived class sets the model explicitly, respect that setting. kwargs.setdefault('form', self.base_form or self.form) # prevent infinite recursion in django 1.6+ if not getattr(self, 'declared_fieldsets', None): kwargs.setdefault('fields', None) return super(PolymorphicChildModelAdmin, self).get_form(request, obj, **kwargs)
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]) 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: if admin_class: admin_class = type( str('DynamicAdminViewPermissionModelAdmin'), (admin_class, AdminViewPermissionModelAdmin), dict(admin_class.__dict__)) else: admin_class = AdminViewPermissionModelAdmin super(AdminViewPermissionAdminSite, self).register([model], admin_class, **options) else: if admin_class: admin_class = type(str('DynamicAdminViewPermissionModelAdmin'), ( admin_class, AdminViewPermissionModelAdmin), dict(admin_class.__dict__)) else: admin_class = AdminViewPermissionModelAdmin super(AdminViewPermissionAdminSite, self).register( model_or_iterable, admin_class, **options)