Django-admin之ModelAdmin methods
ModelAdmin methods
save_model(request, obj, form, change)
此方法为admin界面用户保存model实例时的行为。request为HttpRequest实例,obj为model实例,form为ModelForm实例,change为bool值,取决于model实例是新增的还是修改的。
重写此方法可以做一些pre-save或者post-save行为。
比如,可以把request.user保存为model实例的属性:
from django.contrib import admin class ArticleAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user obj.save()
delete_model(request, obj)
admin界面用户删除model实例时的方法。
save_formset(request, form, formset, change)
admin界面用户保存formset的方法,可以改写:
class ArticleAdmin(admin.ModelAdmin): def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: instance.user = request.user instance.save() formset.save_m2m()
get_ordering(request)
排序。
class PersonAdmin(admin.ModelAdmin): def get_ordering(self, request): if request.user.is_superuser: return ['name', 'rank'] else: return ['name']
get_search_results(request, queryset, search_term)
可以定制查询结果。
save_related(request, form, formsets, change)
formsets是model的inline formsets的列表。model的相关对象保存时的行为。
def save_related(self, request, form, formsets, change): """ Given the ``HttpRequest``, the parent ``ModelForm`` instance, the list of inline formsets and a boolean value based on whether the parent is being added or changed, save the related objects to the database. Note that at this point save_form() and save_model() have already been called. """ form.save_m2m() for formset in formsets: self.save_formset(request, form, formset, change=change)
get_readonly_fields(request, obj=None)
返回只读字段。
get_prepopulated_fields(request, obj=None)
返回预置字段。
get_list_display(request)
返回list_display。
get_list_display_links(request, list_display)
返回list_display_link。
get_fields(request, obj=None)
返回fields。
get_fieldsets(request, obj=None)
返回fieldsets。
get_list_filter(request)
返回list_filter。
get_search_fields(request)
返回search_fields。
get_inline_instances(request, obj=None)
返回InlineModelAdmin对象的列表或元组
class MyModelAdmin(admin.ModelAdmin): def get_inline_instances(self, request, obj=None): return [inline(self.model, self.admin_site) for inline in self.inlines]
get_urls()
返回ModelAdmin的可用urls。
class MyModelAdmin(admin.ModelAdmin): def get_urls(self): urls = super(MyModelAdmin, self).get_urls() my_urls = patterns('', (r'^my_view/$', self.my_view) ) return my_urls + urls def my_view(self, request): # custom view which should return an HttpResponse pass
上面my_view方法的路径就是 /admin/myapp/mymodel/my_view/ 。
不过上面的例子中无验证和缓存,要提供验证和缓存:
class MyModelAdmin(admin.ModelAdmin): def get_urls(self): urls = super(MyModelAdmin, self).get_urls() my_urls = patterns('', (r'^my_view/$', self.admin_site.admin_view(self.my_view)) ) return my_urls + urls
如果页面可缓存而还是要进行权限验证:
(r'^my_view/$', self.admin_site.admin_view(self.my_view, cacheable=True))
get_form(request, obj=None, **kwargs)
返回add和change view使用的ModelForm。下面用户非superuser时会隐藏一些字段。
class MyModelAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): self.exclude = [] if not request.user.is_superuser: self.exclude.append('field_to_hide') return super(MyModelAdmin, self).get_form(request, obj, **kwargs)
get_formsets(request, obj=None)
Yields InlineModelAdmins for use in admin add and change views.
如果只想在the change view中展示一个特殊的inline:
class MyModelAdmin(admin.ModelAdmin): inlines = [MyInline, SomeOtherInline] def get_formsets(self, request, obj=None): for inline in self.get_inline_instances(request, obj): # hide MyInline in the add view if isinstance(inline, MyInline) and obj is None: continue yield inline.get_formset(request, obj)
get_formsets_with_inlines(request, obj=None)
Yields (FormSet, InlineModelAdmin) pairs for use in admin add and change views.
如果只想在the change view中展示一个特殊的inline:
class MyModelAdmin(admin.ModelAdmin): inlines = [MyInline, SomeOtherInline] def get_formsets_with_inlines(self, request, obj=None): for inline in self.get_inline_instances(request, obj): # hide MyInline in the add view if isinstance(inline, MyInline) and obj is None: continue yield inline.get_formset(request, obj), inline
formfield_for_foreignkey(db_field, request, **kwargs)
Foreignkey字段使用的默认formfield. 根据不同的用户返回不同的子集:
class MyModelAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "car": kwargs["queryset"] = Car.objects.filter(owner=request.user) return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
formfield_for_manytomany(db_field, request, **kwargs)
类似于formfield_for_foreignkey,这个方法用于many to many字段.:
class MyModelAdmin(admin.ModelAdmin): def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "cars": kwargs["queryset"] = Car.objects.filter(owner=request.user) return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
ModelAdmin.formfield_for_choice_field(db_field, request, **kwargs)
类似于formfield_for_foreignkey和formfield_for_manytomany,这个方法用于choices:
class MyModelAdmin(admin.ModelAdmin): def formfield_for_choice_field(self, db_field, request, **kwargs): if db_field.name == "status": kwargs['choices'] = ( ('accepted', 'Accepted'), ('denied', 'Denied'), ) if request.user.is_superuser: kwargs['choices'] += (('ready', 'Ready for deployment'),) return super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)
ModelAdmin.get_changelist(request, **kwargs)
返回changelist页面使用的Changelis类. 缺省django.contrib.admin.views.main.ChangeList。
ModelAdmin.get_changelist_form(request, **kwargs)
返回changelist页面使用的ModelForm类。
from django import forms class MyForm(forms.ModelForm): pass class MyModelAdmin(admin.ModelAdmin): def get_changelist_form(self, request, **kwargs): return MyForm
ModelAdmin.get_changelist_formset(request, **kwargs)
返回changelist页面使用的ModelFormSet类。
from django.forms.models import BaseModelFormSet class MyAdminFormSet(BaseModelFormSet): pass class MyModelAdmin(admin.ModelAdmin): def get_changelist_formset(self, request, **kwargs): kwargs['formset'] = MyAdminFormSet return super(MyModelAdmin, self).get_changelist_formset(request, **kwargs)
ModelAdmin.has_add_permission(request)
是否具有add权限。
ModelAdmin.has_change_permission(request, obj=None)
是否具有change权限。
ModelAdmin.has_delete_permission(request, obj=None)
是否具有delete权限。
ModelAdmin.get_queryset(request)
返回admin界面可编辑的model QuerySet集。 根据不同的user返回不同的结果:
class MyModelAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(MyModelAdmin, self).get_queryset(request) if request.user.is_superuser: return qs return qs.filter(author=request.user)
ModelAdmin.message_user(request, message, level=messages.INFO, extra_tags='', fail_silently=False)
向使用django.contrib.messages backend的用户发送信息。
ModelAdmin.get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True)
返回一个分页实例。Returns an instance of the paginator to use for this view. By default, instantiates an instance of paginator.
ModelAdmin.response_add(request, obj, post_url_continue=None)
决定add_view()的HttpResponse,model被创建后运行。
ModelAdmin.response_change(request, obj)
决定change_view()的HttpResponse,model被修改后运行。
ModelAdmin.response_delete(request, obj_display)
决定delete_view()的HttpResponse,model被删除后运行。
obj_display是被删除对象的name。
ModelAdmin.get_changeform_initial_data(request)
A hook for the initial data on admin change forms. By default, fields are given initial values from GET parameters. For instance, ?name=initial_value will set the name field’s initial value to be initial_value.
This method should return a dictionary in the form {'fieldname': 'fieldval'}:
def get_changeform_initial_data(self, request): return {'name': 'custom_initial_value'}
Other methods
ModelAdmin.add_view(request, form_url='', extra_context=None)
Django view for the model instance addition page. See note below.
ModelAdmin.change_view(request, object_id, form_url='', extra_context=None)
Django view for the model instance edition page. See note below.
ModelAdmin.changelist_view(request, extra_context=None)
Django view for the model instances change list/actions page. See note below.
ModelAdmin.delete_view(request, object_id, extra_context=None)
Django view for the model instance(s) deletion confirmation page. See note below.
ModelAdmin.history_view(request, object_id, extra_context=None)
Django view for the page that shows the modification history for a given model instance.
这5个方法是被实际的设定为django的view方法的。可以重构,一般是添加渲染view使用的模板的context data:
class MyModelAdmin(admin.ModelAdmin): # A template for a very customized change view: change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html' def get_osm_info(self): # ... pass def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} extra_context['osm_data'] = self.get_osm_info() return super(MyModelAdmin, self).change_view(request, object_id, form_url, extra_context=extra_context)
ModelAdmin asset definitions
为ModelAdmin的 add/change views添加js和css:
class ArticleAdmin(admin.ModelAdmin): class Media: css = { "all": ("my_styles.css",) } js = ("my_code.js",)
Adding custom validation to the admin
定制form:
class MyArticleAdminForm(forms.ModelForm): def clean_name(self): # do something that validates your data return self.cleaned_data["name"] class ArticleAdmin(admin.ModelAdmin): form = MyArticleAdminForm