Django之model admin自定义后台管理

Admin管理界面是django的杀手级应用。它读取你模式中的元数据,然后提供给你一个强大而且可以使用的界面,网站管理者可以用它立即向网站中添加内容。

比如,数据表如下:

  1.  
    from django.db import models
  2.  
     
  3.  
    # Create your models here.
  4.  
    class Author(models.Model):
  5.  
    #作者
  6.  
    name = models.CharField(max_length=30,verbose_name='姓名')#姓名
  7.  
    age = models.CharField(max_length=30,verbose_name='年龄')#年龄
  8.  
    phone = models.CharField(max_length=11,verbose_name='手机号')#手机号
  9.  
    email = models.EmailField(verbose_name='邮箱')#邮箱
  10.  
    def __str__(self):
  11.  
    return self.name
  12.  
    class Meta:
  13.  
    verbose_name = '作者'
  14.  
    verbose_name_plural = '作者'
  15.  
    class Publisher(models.Model):#出版社
  16.  
    name = models.CharField(max_length=30,verbose_name='出版社')#出版社姓名
  17.  
    address = models.CharField(max_length=50,verbose_name='地址')#出版社地址
  18.  
    city = models.CharField(max_length=60,verbose_name='城市')#出版社城市
  19.  
    state_province = models.CharField(max_length=30,verbose_name='省份')#省份
  20.  
    country = models.CharField(max_length=50,verbose_name='国家')#国家
  21.  
    website = models.URLField(verbose_name='官网')#官网
  22.  
    def __str__(self):
  23.  
    return self.name
  24.  
    class Meta:
  25.  
    verbose_name = '出版社'
  26.  
    verbose_name_plural = '出版社'
  27.  
    class Book(models.Model):#书
  28.  
    name = models.CharField(max_length=60,verbose_name='书名')#书名
  29.  
    author = models.ManyToManyField(Author,verbose_name='作者')#关联作者
  30.  
    publisher = models.ForeignKey(Publisher,verbose_name='出版社')#关联
  31.  
    publication_date = models.DateField(verbose_name='出版时间')#时间
  32.  
    def __str__(self):
  33.  
    return self.name
  34.  
    class Meta:
  35.  
    verbose_name = '书名'
  36.  
    verbose_name_plural = '书名'

要使用admin,可以按照下面的步骤:

  1. 'django.contrib.admin'加入setting的INSTALLED_APPS配置中。
  2. 保证INSTALLED_APPS中,包含'django.contrib.auth''django.contrib.contenttypes''django.contrib.messages''django.contrib.sessions.',Django的admin需要这4个包。

    settings.py:

    1.  
      INSTALLED_APPS = [
    2.  
      'django.contrib.admin',
    3.  
      'django.contrib.auth',
    4.  
      'django.contrib.contenttypes',
    5.  
      'django.contrib.sessions',
    6.  
      'django.contrib.messages',
    7.  
      'django.contrib.staticfiles',
    8.  
      'book',
    9.  
      ]
  3. 'django.contrib.messages.context_processors.messages'添加到 TEMPLATE_CONTEXT_PROCESSORS中,并确保MIDDLEWARE_CLASSES 包含'django.contrib.auth.middleware.AuthenticationMiddleware''django.contrib.messages.middleware.MessageMiddleware'。 (默认已加入)
  4. 确定哪些Model需要应用到admin中。
  5. 为每个需要admin的app中的admin.py中创建一个ModelAdmin。
  6. 注册Model及ModelAdmin:

    1.  
      from django.contrib import admin
    2.  
      from myproject.myapp.models import Author
    3.  
       
    4.  
      class AuthorAdmin(admin.ModelAdmin):
    5.  
      pass
    6.  
      admin.site.register(Author, AuthorAdmin)
  7. 将admin访问配置在URLconf中

    1.  
      from django.contrib import admin
    2.  
      admin.autodiscover()
    3.  
       
    4.  
      # And include this URLpattern...
    5.  
      urlpatterns = patterns('',
    6.  
      # ...
    7.  
      (r'^admin/', include(admin.site.urls)),
    8.  
      # ...
    9.  
      )
  8. 运行python manage.py migrate提醒创建superuser后就可以访问 http://127.0.0.1:8000/admin/ 了。其实就是生成表结构的过程:

    1.  
      python manage.py makemigrations
    2.  
      python manage.py migrate
    3.  
      python manage.py createsuperuser

    ModelAdmin对象

    register装饰器

register(*models[, site=django.admin.sites.site])

1.7中新添加。Model和ModelAdmin可以这样注册:

  1.  
    from django.contrib import admin
  2.  
    from .models import Author
  3.  
     
  4.  
    @admin.register(Author)
  5.  
    class AuthorAdmin(admin.ModelAdmin):
  6.  
    pass

可以一次注册多个Model,并且可以使用自己定制的AdminSite:

  1.  
    from django.contrib import admin
  2.  
    from .models import Author, Reader, Editor
  3.  
    from myproject.admin_site import custom_admin_site
  4.  
     
  5.  
    @admin.register(Author, Reader, Editor, site=custom_admin_site)
  6.  
    class PersonAdmin(admin.ModelAdmin):
  7.  
    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是排除。

  1.  
    from django.contrib import admin
  2.  
     
  3.  
    class AuthorAdmin(admin.ModelAdmin):
  4.  
    fields = ('name', 'title')
  5.  
     
  6.  
    class AuthorAdmin(admin.ModelAdmin):
  7.  
    exclude = ('birth_date',)

可以将一些字段放在同一行,如下url和title字段放在同一行:

  1.  
    class FlatPageAdmin(admin.ModelAdmin):
  2.  
    fields = (('url', 'title'), 'content')

fieldsets

fieldsets是双元元组(name, field_options)的列表,可以将字段分块:

  1.  
    from django.contrib import admin
  2.  
     
  3.  
    class FlatPageAdmin(admin.ModelAdmin):
  4.  
    fieldsets = (
  5.  
    (None, {
  6.  
    'fields': ('url', 'title', 'content', 'sites')
  7.  
    }),
  8.  
    ('Advanced options', {
  9.  
    'classes': ('collapse',),
  10.  
    'fields': ('enable_comments', 'registration_required', 'template_name')
  11.  
    }),
  12.  
    )

name

name是块的标题,field_options是一个字典。

field_options

field_options的key有下面几种:

fields

字段名称的元组,在fieldset中展示:

  1.  
    {
  2.  
    'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
  3.  
    }

classes

提供给fieldset的额外CSS类的列表。

description

可以在fieldset顶部额外展示的文本。

filter_horizontal / filter_vertical

Model有ManyToManyField字段时,使用filter_horizontal,(支持拖拽),filter_vertical可以从现有的选项中多选。一个为横排,一个为竖排。

form

使用的表单.

  1.  
    from django import forms
  2.  
    from django.contrib import admin
  3.  
    from myapp.models import Person
  4.  
     
  5.  
    class PersonForm(forms.ModelForm):
  6.  
     
  7.  
    class Meta:
  8.  
    model = Person
  9.  
    exclude = ['name']
  10.  
     
  11.  
    class PersonAdmin(admin.ModelAdmin):
  12.  
    exclude = ['age']
  13.  
    form = PersonForm

发生冲突时,ModelAdmin优先。上面的例子中age会被排除,但name会在页面中展示。

formfield_overrides

可以覆盖Model表单界面的一些字段的选项,为一些特定类型的字段添加自己定制的部件,比如,想为自己Model的TextField字段使用富文本编辑器:

  1.  
    from django.db import models
  2.  
    from django.contrib import admin
  3.  
     
  4.  
    # Import our custom widget and our model from where they're defined
  5.  
    from myapp.widgets import RichTextEditorWidget
  6.  
    from myapp.models import MyModel
  7.  
     
  8.  
    class MyModelAdmin(admin.ModelAdmin):
  9.  
    formfield_overrides = {
  10.  
    models.TextField: {'widget': RichTextEditorWidget},
  11.  
    }

list_display

Model的change list页面可以展示的字段,如果不设置list_display,admin界面会自动展示Model的__unicode__()结果,在python3中为__str__()

list_display中有4种值:

model的一个字段

list_display = ('first_name', 'last_name')

一个可调用的以model为参数的函数

  1.  
    def upper_case_name(obj):
  2.  
    return ("%s %s" % (obj.first_name, obj.last_name)).upper()
  3.  
    upper_case_name.short_description = 'Name'
  4.  
     
  5.  
    class PersonAdmin(admin.ModelAdmin):
  6.  
    list_display = (upper_case_name,) 

ModelAdmin的一个属性,类似于可调用函数

  1.  
    class PersonAdmin(admin.ModelAdmin):
  2.  
    list_display = ('upper_case_name',)
  3.  
     
  4.  
    def upper_case_name(self, obj):
  5.  
    return ("%s %s" % (obj.first_name, obj.last_name)).upper()
  6.  
    upper_case_name.short_description = 'Name'

Model的一个属性,类似于可调用函数

  1.  
    from django.db import models
  2.  
    from django.contrib import admin
  3.  
     
  4.  
    class Person(models.Model):
  5.  
    name = models.CharField(max_length=50)
  6.  
    birthday = models.DateField()
  7.  
     
  8.  
    def decade_born_in(self):
  9.  
    return self.birthday.strftime('%Y')[:3] + "0's"
  10.  
    decade_born_in.short_description = 'Birth decade'
  11.  
     
  12.  
    class PersonAdmin(admin.ModelAdmin):
  13.  
    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转义用户的输入:

    1.  
      from django.db import models
    2.  
      from django.contrib import admin
    3.  
      from django.utils.html import format_html
    4.  
       
    5.  
      class Person(models.Model):
    6.  
      first_name = models.CharField(max_length=50)
    7.  
      last_name = models.CharField(max_length=50)
    8.  
      color_code = models.CharField(max_length=6)
    9.  
       
    10.  
      def colored_name(self):
    11.  
      return format_html('<span style="color: #{0};">{1} {2}</span>',
    12.  
      self.color_code,
    13.  
      self.first_name,
    14.  
      self.last_name)
    15.  
       
    16.  
      colored_name.allow_tags = True
    17.  
       
    18.  
      class PersonAdmin(admin.ModelAdmin):
    19.  
      list_display = ('first_name', 'last_name', 'colored_name')
  • 如果提供的字符串是Model或者ModelAdmin的方法或者一个可调用函数,并且返回True或者False,可以将方法的boolean属性设为True。这样页面上会展示on或者off图标。

    1.  
      from django.db import models
    2.  
      from django.contrib import admin
    3.  
       
    4.  
      class Person(models.Model):
    5.  
      first_name = models.CharField(max_length=50)
    6.  
      birthday = models.DateField()
    7.  
       
    8.  
      def born_in_fifties(self):
    9.  
      return self.birthday.strftime('%Y')[:3] == '195'
    10.  
      born_in_fifties.boolean = True
    11.  
       
    12.  
      class PersonAdmin(admin.ModelAdmin):
    13.  
      list_display = ('name', 'born_in_fifties') 
  • Model的__str__或者__unicode__方法也可以使用

    list_display = ('__str__', 'some_other_field')
  • 如果list_display中的项不是数据库的实际字段,那么不可以以此项排序。反之,则可以以此项排序,可以通过设置 admin_order_field属性指出这个事实。

    1.  
      from django.db import models
    2.  
      from django.contrib import admin
    3.  
      from django.utils.html import format_html
    4.  
       
    5.  
      class Person(models.Model):
    6.  
      first_name = models.CharField(max_length=50)
    7.  
      color_code = models.CharField(max_length=6)
    8.  
       
    9.  
      def colored_first_name(self):
    10.  
      return format_html('<span style="color: #{0};">{1}</span>',
    11.  
      self.color_code,
    12.  
      self.first_name)
    13.  
       
    14.  
      colored_first_name.allow_tags = True
    15.  
      colored_first_name.admin_order_field = 'first_name'
    16.  
       
    17.  
      class PersonAdmin(admin.ModelAdmin):
    18.  
      list_display = ('first_name', 'colored_first_name')

    这样试图以colored_first_name排序时,django会以first_name排序。可以反向排序:

    colored_first_name.admin_order_field = '-first_name'
  • list_display中的项也可以是特性:

    1.  
      class Person(object):
    2.  
      first_name = models.CharField(max_length=50)
    3.  
      last_name = models.CharField(max_length=50)
    4.  
       
    5.  
      def my_property(self):
    6.  
      return self.first_name + ' ' + self.last_name
    7.  
      my_property.short_description = "Full name of the person"
    8.  
       
    9.  
      full_name = property(my_property)
    10.  
       
    11.  
      class PersonAdmin(admin.ModelAdmin):
    12.  
      list_display = ('full_name',) 

其中的字段会被链接到mode的change页面

  1.  
    class PersonAdmin(admin.ModelAdmin):
  2.  
    list_display = ('first_name', 'last_name', 'birthday')
  3.  
    list_display_links = ('first_name', 'last_name')

list_editable

其中的字段在change list页面是可以被更改的。在其中的字段也必须在list_display中。

list_filter

其中的字段可以作为过滤器过滤model 。可以是相关域。页面右边会出现相应的过滤器选项

  1.  
    class PersonAdmin(admin.UserAdmin):
  2.  
    list_filter = ('company__name',)

list_max_show_all

show all页面上的model数目,缺省200。

list_per_page

每个change list页面的model数目,缺省100。

与select_related()有关。

ordering

排序。

  1.  
    from django.contrib import admin
  2.  
     
  3.  
    # Register your models here.
  4.  
    from book import models
  5.  
     
  6.  
    class AuthorAdmin(admin.ModelAdmin):
  7.  
    list_display = ('name','age','phone','email')
  8.  
    search_fields = ('name','age','phone','email')
  9.  
    fields = ('name','age','email','phone')
  10.  
    #按照年龄排序
  11.  
    ordering = ('age',)
  12.  
    #将作者注册到admin后台
  13.  
    admin.site.register(models.Author,AuthorAdmin)

paginator

使用的分页。缺省django.core.paginator.Paginator 。

prepopulated_fields

预置字段。

radio_fields

使用radio-button代替select-box( ForeignKey或者有choices选项时)。

  1.  
    class PersonAdmin(admin.ModelAdmin):
  2.  
    radio_fields = {"group": admin.VERTICAL}

raw_id_fields

会展示其中字段的id,用于ForeignKey或者ManyToManyField。

  1.  
    class ArticleAdmin(admin.ModelAdmin):
  2.  
    raw_id_fields = ("newspaper",)

readonly_fields

只可读不可编辑的字段。也可以是方法:

  1.  
    from django.contrib import admin
  2.  
    from django.utils.html import format_html_join
  3.  
    from django.utils.safestring import mark_safe
  4.  
     
  5.  
    class PersonAdmin(admin.ModelAdmin):
  6.  
    readonly_fields = ('address_report',)
  7.  
     
  8.  
    def address_report(self, instance):
  9.  
    # assuming get_full_address() returns a list of strings
  10.  
    # for each line of the address and you want to separate each
  11.  
    # line by a linebreak
  12.  
    return format_html_join(
  13.  
    mark_safe('<br/>'),
  14.  
    '{0}',
  15.  
    ((line,) for line in instance.get_full_address()),
  16.  
    ) or "<span class='errors'>I can't determine this address.</span>"
  17.  
     
  18.  
    # short_description functions like a model field's verbose_name
  19.  
    address_report.short_description = "Address"
  20.  
    # in this example, we have used HTML tags in the output
  21.  
    address_report.allow_tags = True

save_as

设为Ture时,change页面的 "Save and add another"按钮会被"Save as"代替。

save_on_top

设为Ture时,change页面的顶端也会有save按钮。

search_fields

可搜索字段。这样就可以按照标题或内容搜索了

  1.  
    from django.contrib import admin
  2.  
     
  3.  
    # Register your models here.
  4.  
    from book import models
  5.  
     
  6.  
    class AuthorAdmin(admin.ModelAdmin):
  7.  
    list_display = ('name','age','phone','email')
  8.  
    #添加搜索功能
  9.  
    search_fields = ('name','age','phone','email')
  10.  
    #将作者注册到admin后台
  11.  
    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实例的属性:

  1.  
    from django.contrib import admin
  2.  
     
  3.  
    class ArticleAdmin(admin.ModelAdmin):
  4.  
    def save_model(self, request, obj, form, change):
  5.  
    obj.user = request.user
  6.  
    obj.save()

delete_model(request, obj)

admin界面用户删除model实例时的方法。

save_formset(request, form, formset, change)

admin界面用户保存formset的方法,可以改写:

  1.  
    class ArticleAdmin(admin.ModelAdmin):
  2.  
    def save_formset(self, request, form, formset, change):
  3.  
    instances = formset.save(commit=False)
  4.  
    for instance in instances:
  5.  
    instance.user = request.user
  6.  
    instance.save()
  7.  
    formset.save_m2m()

get_ordering(request)

排序

  1.  
    class PersonAdmin(admin.ModelAdmin):
  2.  
     
  3.  
    def get_ordering(self, request):
  4.  
    if request.user.is_superuser:
  5.  
    return ['name', 'rank']
  6.  
    else:
  7.  
    return ['name']

get_search_results(request, queryset, search_term)

可以定制查询结果

save_related(request, form, formsets, change)

formsets是model的inline formsets的列表。model的相关对象保存时的行为。

  1.  
    def save_related(self, request, form, formsets, change):
  2.  
    """
  3.  
    Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
  4.  
    list of inline formsets and a boolean value based on whether the
  5.  
    parent is being added or changed, save the related objects to the
  6.  
    database. Note that at this point save_form() and save_model() have
  7.  
    already been called.
  8.  
    """
  9.  
    form.save_m2m()
  10.  
    for formset in formsets:
  11.  
    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对象的列表或元组

  1.  
    class MyModelAdmin(admin.ModelAdmin):
  2.  
    def get_inline_instances(self, request, obj=None):
  3.  
    return [inline(self.model, self.admin_site) for inline in self.inlines]

get_urls()

返回ModelAdmin的可用urls。

  1.  
    class MyModelAdmin(admin.ModelAdmin):
  2.  
    def get_urls(self):
  3.  
    urls = super(MyModelAdmin, self).get_urls()
  4.  
    my_urls = patterns('',
  5.  
    (r'^my_view/$', self.my_view)
  6.  
    )
  7.  
    return my_urls + urls
  8.  
     
  9.  
    def my_view(self, request):
  10.  
    # custom view which should return an HttpResponse
  11.  
    pass

上面my_view方法的路径就是 /admin/myapp/mymodel/my_view/ 。

不过上面的例子中无验证和缓存,要提供验证和缓存:

  1.  
    class MyModelAdmin(admin.ModelAdmin):
  2.  
    def get_urls(self):
  3.  
    urls = super(MyModelAdmin, self).get_urls()
  4.  
    my_urls = patterns('',
  5.  
    (r'^my_view/$', self.admin_site.admin_view(self.my_view))
  6.  
    )
  7.  
    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时会隐藏一些字段。

  1.  
    class MyModelAdmin(admin.ModelAdmin):
  2.  
    def get_form(self, request, obj=None, **kwargs):
  3.  
    self.exclude = []
  4.  
    if not request.user.is_superuser:
  5.  
    self.exclude.append('field_to_hide')
  6.  
    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:

  1.  
    class MyModelAdmin(admin.ModelAdmin):
  2.  
    inlines = [MyInline, SomeOtherInline]
  3.  
     
  4.  
    def get_formsets(self, request, obj=None):
  5.  
    for inline in self.get_inline_instances(request, obj):
  6.  
    # hide MyInline in the add view
  7.  
    if isinstance(inline, MyInline) and obj is None:
  8.  
    continue
  9.  
    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:

  1.  
    class MyModelAdmin(admin.ModelAdmin):
  2.  
    inlines = [MyInline, SomeOtherInline]
  3.  
     
  4.  
    def get_formsets_with_inlines(self, request, obj=None):
  5.  
    for inline in self.get_inline_instances(request, obj):
  6.  
    # hide MyInline in the add view
  7.  
    if isinstance(inline, MyInline) and obj is None:
  8.  
    continue
  9.  
    yield inline.get_formset(request, obj), inline

formfield_for_foreignkey(db_field, request, **kwargs)
Foreignkey字段使用的默认formfield. 根据不同的用户返回不同的子集:

  1.  
    class MyModelAdmin(admin.ModelAdmin):
  2.  
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
  3.  
    if db_field.name == "car":
  4.  
    kwargs["queryset"] = Car.objects.filter(owner=request.user)
  5.  
    return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

formfield_for_manytomany(db_field, request, **kwargs)
类似于formfield_for_foreignkey,这个方法用于many to many字段.:

  1.  
    class MyModelAdmin(admin.ModelAdmin):
  2.  
    def formfield_for_manytomany(self, db_field, request, **kwargs):
  3.  
    if db_field.name == "cars":
  4.  
    kwargs["queryset"] = Car.objects.filter(owner=request.user)
  5.  
    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:

  1.  
    class MyModelAdmin(admin.ModelAdmin):
  2.  
    def formfield_for_choice_field(self, db_field, request, **kwargs):
  3.  
    if db_field.name == "status":
  4.  
    kwargs['choices'] = (
  5.  
    ('accepted', 'Accepted'),
  6.  
    ('denied', 'Denied'),
  7.  
    )
  8.  
    if request.user.is_superuser:
  9.  
    kwargs['choices'] += (('ready', 'Ready for deployment'),)
  10.  
    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类。

  1.  
    from django import forms
  2.  
     
  3.  
    class MyForm(forms.ModelForm):
  4.  
    pass
  5.  
     
  6.  
    class MyModelAdmin(admin.ModelAdmin):
  7.  
    def get_changelist_form(self, request, **kwargs):
  8.  
    return MyForm

ModelAdmin.get_changelist_formset(request, **kwargs)
返回changelist页面使用的ModelFormSet类。

  1.  
    from django.forms.models import BaseModelFormSet
  2.  
     
  3.  
    class MyAdminFormSet(BaseModelFormSet):
  4.  
    pass
  5.  
     
  6.  
    class MyModelAdmin(admin.ModelAdmin):
  7.  
    def get_changelist_formset(self, request, **kwargs):
  8.  
    kwargs['formset'] = MyAdminFormSet
  9.  
    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返回不同的结果:

  1.  
    class MyModelAdmin(admin.ModelAdmin):
  2.  
    def get_queryset(self, request):
  3.  
    qs = super(MyModelAdmin, self).get_queryset(request)
  4.  
    if request.user.is_superuser:
  5.  
    return qs
  6.  
    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'}:

  1.  
    def get_changeform_initial_data(self, request):
  2.  
    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:

  1.  
    class MyModelAdmin(admin.ModelAdmin):
  2.  
     
  3.  
    # A template for a very customized change view:
  4.  
    change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'
  5.  
     
  6.  
    def get_osm_info(self):
  7.  
    # ...
  8.  
    pass
  9.  
     
  10.  
    def change_view(self, request, object_id, form_url='', extra_context=None):
  11.  
    extra_context = extra_context or {}
  12.  
    extra_context['osm_data'] = self.get_osm_info()
  13.  
    return super(MyModelAdmin, self).change_view(request, object_id,
  14.  
    form_url, extra_context=extra_context)

ModelAdmin asset definitions

为ModelAdmin的 add/change views添加js和css:

  1.  
    class ArticleAdmin(admin.ModelAdmin):
  2.  
    class Media:
  3.  
    css = {
  4.  
    "all": ("my_styles.css",)
  5.  
    }
  6.  
    js = ("my_code.js",)

Adding custom validation to the admin

定制form:

  1.  
    class MyArticleAdminForm(forms.ModelForm):
  2.  
    def clean_name(self):
  3.  
    # do something that validates your data
  4.  
    return self.cleaned_data["name"]
  5.  
    class ArticleAdmin(admin.ModelAdmin):
  6.  
    form = MyArticleAdminForm
 
 
 
标签
posted @ 2018-08-31 22:06  核电站  阅读(3717)  评论(0编辑  收藏  举报