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

  

Django admin site(二)ModelAdmin methods的更多相关文章

  1. Django admin site(一)ModelAdmin Options

    Admin管理界面是django的杀手级应用.它读取你模式中的元数据,然后提供给你一个强大而且可以使用的界面,网站管理者可以用它立即向网站中添加内容. 要使用admin,可以按照下面的步骤: 将'dj ...

  2. Django Admin site 显示问题

    Django Admin site 显示问题 今天配置了一下Django admin site,可是admin site的显示有一些问题,当我打开源码.訪问里面的admin 的css 文件时候,htt ...

  3. django admin site (三)

    1.自定义模板设置: ModelAdmin. add_form_template Path to a custom template, used by add_view(). ModelAdmin. ...

  4. Django admin site(三)InlineModelAdmin

    InlineModelAdmin class InlineModelAdminclass TabularInlineclass StackedInline 举例,有两个Model: from djan ...

  5. Django admin site应用

    django自带的admin后台管理,可以实现对数据库表的增删改查,用起来十分方便.其使用和配置主要分为三个步骤: 1,创建超级用户 需要创建超级用户来登陆admin后台系统,在命令行中输入 pyth ...

  6. django admin site配置(二)

    1. ModelAdmin.inlines 将有外键的子类包含进视图 ,实例: class Author(models.Model): name = models.CharField(max_leng ...

  7. Django实现自定义template页面并在admin site的app模块中加入自定义跳转链接

    在文章 Django实现自定义template页面并在admin site的app模块中加入自定义跳转链接(一) 中我们成功的为/feedback/feedback_stats/路径自定义了使用tem ...

  8. Django admin 权威指南(一)

    版本: Django 1.10 此部分由官方文档<6.5.1 The Django admin site>翻译而来. 6.5.1.1 概览 默认情况下,使用startproject的时候, ...

  9. 08/27 Django admin相关

    一.django-admin的简单回顾: admin: Django的后台数据管理的web版本 1.admin a:models.py - 创建表 b:admin.py - 注册表    admin. ...

随机推荐

  1. WPF自定义控件(二)——TextBox

    和之前一样,先来看看效果: 这个TextBox可设置水印,可设置必填和正则表达式验证. 验证?没错,就是验证! 就是在输入完成后,控件一旦失去焦点就会自动验证!会根据我开放出来的“是否可以为空”属性进 ...

  2. linux 获取cpu 个数

    sysconf( )有unistd.h提供,要使用该函数需要#include<unistd.h>,其参数可以是_SC_NPROCESSORS_CONF,也可以是_SC_NPROCESSOR ...

  3. Python的循环

    循环是一个结构,导致一个程序要重复一定的次数 条件循环也一样,当条件变为假,循环结束 For循环 在python for循环遍历序列,如一个列表或一个字符. for循环语法:   ——for iter ...

  4. Linux磁盘空间爆满,MySQL无法启动

    OS: Cent OS 6.3 DB: 5.5.14 看到一个帖子,在服务器上安装了oracle和mysql数据库,mysql数据库忘记开启innodb_file_per_table,导致插入测试数据 ...

  5. MySQL 库大小、表大小、索引大小查询命令

    1.进去指定schema 数据库(存放了其他的数据库的信息)     mysql> use information_schema; 2.查询所有数据的大小      mysql> sele ...

  6. sharepoint 2010

    Technical diagrams (SharePoint Server 2010) http://technet.microsoft.com/en-us/library/cc263199(offi ...

  7. cocos2dx中的格子地图TileMap

    格子地图的优点: a.节省内存,我们知道对于一款游戏来说,如果以图片来作为地图的话,对于神庙逃亡,魂斗罗这样的场景很多,地图很长的游戏显然不现实,因为图片很占内存,但是这些游戏的地图有一个特点就是:重 ...

  8. Interview-Largest independent set in binary tree.

    BT(binary tree), want to find the LIS(largest independent set) of the BT. LIS: if the current node i ...

  9. android开发 socket接收图片并保存

    逻辑:接收到socket之后需要将socket发送的图片数据保存下来并通知handler更新界面 关键代码: public void readImage(Socket socket) { try { ...

  10. android开发获取屏幕高度和宽度

    宽度:getWindowManager().getDefaultDisplay().getWidth(); 高度:getWindowManager().getDefaultDisplay().getH ...