Admin管理界面是django的杀手级应用。它读取你模式中的元数据,然后提供给你一个强大而且可以使用的界面,网站管理者可以用它立即向网站中添加内容。
比如,数据表如下:
from django.db import models
# Create your models here.
class Author(models.Model):
#作者
name = models.CharField(max_length=30,verbose_name='姓名')#姓名
age = models.CharField(max_length=30,verbose_name='年龄')#年龄
phone = models.CharField(max_length=11,verbose_name='手机号')#手机号
email = models.EmailField(verbose_name='邮箱')#邮箱
def __str__(self):
return self.name
class Meta:
verbose_name = '作者'
verbose_name_plural = '作者'
class Publisher(models.Model):#出版社
name = models.CharField(max_length=30,verbose_name='出版社')#出版社姓名
address = models.CharField(max_length=50,verbose_name='地址')#出版社地址
city = models.CharField(max_length=60,verbose_name='城市')#出版社城市
state_province = models.CharField(max_length=30,verbose_name='省份')#省份
country = models.CharField(max_length=50,verbose_name='国家')#国家
website = models.URLField(verbose_name='官网')#官网
def __str__(self):
return self.name
class Meta:
verbose_name = '出版社'
verbose_name_plural = '出版社'
class Book(models.Model):#书
name = models.CharField(max_length=60,verbose_name='书名')#书名
author = models.ManyToManyField(Author,verbose_name='作者')#关联作者
publisher = models.ForeignKey(Publisher,verbose_name='出版社')#关联
publication_date = models.DateField(verbose_name='出版时间')#时间
def __str__(self):
return self.name
class Meta:
verbose_name = '书名'
verbose_name_plural = '书名'
要使用admin,可以按照下面的步骤:
-
将
'django.contrib.admin'
加入setting的INSTALLED_APPS配置中。 -
保证INSTALLED_APPS中,包含
'django.contrib.auth'
,'django.contrib.contenttypes'
,'django.contrib.messages'
和'django.contrib.sessions.'
,Django的admin需要这4个包。settings.py:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'book', ]
-
将
'django.contrib.messages.context_processors.messages'
添加到TEMPLATE_CONTEXT_PROCESSORS
中,并确保MIDDLEWARE_CLASSES
包含'django.contrib.auth.middleware.AuthenticationMiddleware'
和'django.contrib.messages.middleware.MessageMiddleware'
。 (默认已加入) -
确定哪些Model需要应用到admin中。
-
为每个需要admin的app中的admin.py中创建一个ModelAdmin。
-
注册Model及ModelAdmin:
from django.contrib import admin from myproject.myapp.models import Author class AuthorAdmin(admin.ModelAdmin): pass admin.site.register(Author, AuthorAdmin)
-
将admin访问配置在URLconf中
from django.contrib import admin admin.autodiscover() # And include this URLpattern... urlpatterns = patterns('', # ... (r'^admin/', include(admin.site.urls)), # ... )
-
运行python manage.py migrate提醒创建superuser后就可以访问 http://127.0.0.1:8000/admin/ 了。其实就是生成表结构的过程:
python manage.py makemigrations python manage.py migrate python manage.py createsuperuser
ModelAdmin对象
register装饰器
register(*models[, site=django.admin.sites.site])
1.7中新添加。Model和ModelAdmin可以这样注册:
from django.contrib import admin
from .models import Author
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
pass
可以一次注册多个Model,并且可以使用自己定制的AdminSite:
from django.contrib import admin
from .models import Author, Reader, Editor
from myproject.admin_site import custom_admin_site
@admin.register(Author, Reader, Editor, site=custom_admin_site)
class PersonAdmin(admin.ModelAdmin):
pass
Admin是如何工作的
当把'django.contrib.admin'添加到INSTALLED_APPS后,django会自动查找每个app中的admin.py模块并且import载入。
class apps.AdminConfig
Django 1.7新增.
admin默认的AppConfig类.当django启动时会执行autodiscover()。
class apps.SimpleAdminConfig
Django 1.7新增.
类似于AdminConfig,不会执行autodiscover().
autodiscover()
import每个app的admin.py模块。
Django 1.7改变:
在以前的版本中需要在urls.py中手动启动此方法去寻找每个app的admin.py,1.7后AdminConfig会自动执行此方法。
如果正在使用定制的AdminSite,需要将ModelAdmin的子类载入到自己的代码中并全部注册到定制的AdminSite中。这种情况下需要停止自动discovery(),可以将'django.contrib.admin.apps.SimpleAdminConfig'
代替INSTALLED_APPS中的'django.contrib.admin'
。
ModelAdmin选项
actions
admin actions的列表
actions_on_top / actions_on_bottom
action的位置。
date_hierarchy
将date_hierarchy设成Model的DateField或者DateTimeField,就可以为admin中的此Model添加日期层次。
fields / exclude
决定Model的form中展现哪些字段。fields是包括,exclude是排除。
from django.contrib import admin
class AuthorAdmin(admin.ModelAdmin):
fields = ('name', 'title')
class AuthorAdmin(admin.ModelAdmin):
exclude = ('birth_date',)
可以将一些字段放在同一行,如下url和title字段放在同一行:
class FlatPageAdmin(admin.ModelAdmin):
fields = (('url', 'title'), 'content')
fieldsets
fieldsets是双元元组(name, field_options)的列表,可以将字段分块:
from django.contrib import admin
class FlatPageAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': ('url', 'title', 'content', 'sites')
}),
('Advanced options', {
'classes': ('collapse',),
'fields': ('enable_comments', 'registration_required', 'template_name')
}),
)
name
name是块的标题,field_options是一个字典。
field_options
field_options的key有下面几种:
fields
字段名称的元组,在fieldset中展示:
{
'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
}
classes
提供给fieldset的额外CSS类的列表。
description
可以在fieldset顶部额外展示的文本。
filter_horizontal / filter_vertical
Model有ManyToManyField字段时,使用filter_horizontal,(支持拖拽),filter_vertical可以从现有的选项中多选。一个为横排,一个为竖排。
form
使用的表单.
from django import forms
from django.contrib import admin
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
exclude = ['name']
class PersonAdmin(admin.ModelAdmin):
exclude = ['age']
form = PersonForm
发生冲突时,ModelAdmin优先。上面的例子中age会被排除,但name会在页面中展示。
formfield_overrides
可以覆盖Model表单界面的一些字段的选项,为一些特定类型的字段添加自己定制的部件,比如,想为自己Model的TextField字段使用富文本编辑器:
from django.db import models
from django.contrib import admin
# Import our custom widget and our model from where they're defined
from myapp.widgets import RichTextEditorWidget
from myapp.models import MyModel
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': RichTextEditorWidget},
}
list_display
Model的change list页面可以展示的字段,如果不设置list_display,admin界面会自动展示Model的__unicode__()
结果,在python3中为__str__()
。
list_display中有4种值:
model的一个字段
list_display = ('first_name', 'last_name')
一个可调用的以model为参数的函数
def upper_case_name(obj):
return ("%s %s" % (obj.first_name, obj.last_name)).upper()
upper_case_name.short_description = 'Name'
class PersonAdmin(admin.ModelAdmin):
list_display = (upper_case_name,)
ModelAdmin的一个属性,类似于可调用函数
class PersonAdmin(admin.ModelAdmin):
list_display = ('upper_case_name',)
def upper_case_name(self, obj):
return ("%s %s" % (obj.first_name, obj.last_name)).upper()
upper_case_name.short_description = 'Name'
Model的一个属性,类似于可调用函数
from django.db import models
from django.contrib import admin
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
def decade_born_in(self):
return self.birthday.strftime('%Y')[:3] + "0's"
decade_born_in.short_description = 'Birth decade'
class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'decade_born_in')
list_display之TIPS:
-
如果字段是ForeignKey,会显示外键的__unicode__。
-
不支持ManyToManyField
-
如果是BooleanField,会显示on或者off。
-
如果提供的字符串是Model或者ModelAdmin的方法或者一个可调用函数,django会自动的HTML-escape输出,如果不想转义,可以将方法的allow_tags设为True。为了避免XSS跨站攻击,需要使用format_html转义用户的输入:
from django.db import models from django.contrib import admin from django.utils.html import format_html class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) color_code = models.CharField(max_length=6) def colored_name(self): return format_html('<span style="color: #{0};">{1} {2}</span>', self.color_code, self.first_name, self.last_name) colored_name.allow_tags = True class PersonAdmin(admin.ModelAdmin): list_display = ('first_name', 'last_name', 'colored_name')
-
如果提供的字符串是Model或者ModelAdmin的方法或者一个可调用函数,并且返回True或者False,可以将方法的boolean属性设为True。这样页面上会展示on或者off图标。
from django.db import models from django.contrib import admin class Person(models.Model): first_name = models.CharField(max_length=50) birthday = models.DateField() def born_in_fifties(self): return self.birthday.strftime('%Y')[:3] == '195' born_in_fifties.boolean = True class PersonAdmin(admin.ModelAdmin): list_display = ('name', 'born_in_fifties')
-
Model的__str__或者__unicode__方法也可以使用
list_display = ('__str__', 'some_other_field')
-
如果list_display中的项不是数据库的实际字段,那么不可以以此项排序。反之,则可以以此项排序,可以通过设置 admin_order_field属性指出这个事实。
from django.db import models from django.contrib import admin from django.utils.html import format_html class Person(models.Model): first_name = models.CharField(max_length=50) color_code = models.CharField(max_length=6) def colored_first_name(self): return format_html('<span style="color: #{0};">{1}</span>', self.color_code, self.first_name) colored_first_name.allow_tags = True colored_first_name.admin_order_field = 'first_name' class PersonAdmin(admin.ModelAdmin): list_display = ('first_name', 'colored_first_name')
这样试图以colored_first_name排序时,django会以first_name排序。可以反向排序:
colored_first_name.admin_order_field = '-first_name'
-
list_display中的项也可以是特性:
class Person(object): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def my_property(self): return self.first_name + ' ' + self.last_name my_property.short_description = "Full name of the person" full_name = property(my_property) class PersonAdmin(admin.ModelAdmin): list_display = ('full_name',)
list_display_link
其中的字段会被链接到mode的change页面
class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'birthday')
list_display_links = ('first_name', 'last_name')
list_editable
其中的字段在change list页面是可以被更改的。在其中的字段也必须在list_display中。
list_filter
其中的字段可以作为过滤器过滤model 。可以是相关域。页面右边会出现相应的过滤器选项
class PersonAdmin(admin.UserAdmin):
list_filter = ('company__name',)
list_max_show_all
show all页面上的model数目,缺省200。
list_per_page
每个change list页面的model数目,缺省100。
list_select_related
与select_related()有关。
ordering
排序。
from django.contrib import admin
# Register your models here.
from book import models
class AuthorAdmin(admin.ModelAdmin):
list_display = ('name','age','phone','email')
search_fields = ('name','age','phone','email')
fields = ('name','age','email','phone')
#按照年龄排序
ordering = ('age',)
#将作者注册到admin后台
admin.site.register(models.Author,AuthorAdmin)
paginator
使用的分页。缺省django.core.paginator.Paginator 。
prepopulated_fields
预置字段。
radio_fields
使用radio-button代替select-box( ForeignKey或者有choices选项时)。
class PersonAdmin(admin.ModelAdmin):
radio_fields = {"group": admin.VERTICAL}
raw_id_fields
会展示其中字段的id,用于ForeignKey或者ManyToManyField。
class ArticleAdmin(admin.ModelAdmin):
raw_id_fields = ("newspaper",)
readonly_fields
只可读不可编辑的字段。也可以是方法:
from django.contrib import admin
from django.utils.html import format_html_join
from django.utils.safestring import mark_safe
class PersonAdmin(admin.ModelAdmin):
readonly_fields = ('address_report',)
def address_report(self, instance):
# assuming get_full_address() returns a list of strings
# for each line of the address and you want to separate each
# line by a linebreak
return format_html_join(
mark_safe('<br/>'),
'{0}',
((line,) for line in instance.get_full_address()),
) or "<span class='errors'>I can't determine this address.</span>"
# short_description functions like a model field's verbose_name
address_report.short_description = "Address"
# in this example, we have used HTML tags in the output
address_report.allow_tags = True
save_as
设为Ture时,change页面的 "Save and add another"按钮会被"Save as"代替。
save_on_top
设为Ture时,change页面的顶端也会有save按钮。
search_fields
可搜索字段。这样就可以按照标题或内容搜索了
from django.contrib import admin
# Register your models here.
from book import models
class AuthorAdmin(admin.ModelAdmin):
list_display = ('name','age','phone','email')
#添加搜索功能
search_fields = ('name','age','phone','email')
#将作者注册到admin后台
admin.site.register(models.Author,AuthorAdmin)
view_on_site
是否显示View on site链接。
template options
一些定制admin模板时指定模板所用的选项。
add_form_template
add_view()使用的模板.
change_form_template
change_view()使用的模板.
change_list_template
changelist_view()使用的模板.
delete_confirmation_template
delete_view()使用的模板。
delete_selected_confirmation_template
delete_selected action method 使用的模板。
ModelAdmin.object_history_template
history_view()使用的模板,日志。
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'}
其他方法
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