Welcome to Django Xadmin’s Documentation!¶
A Django admin replacement that you shouldn’t miss
Installation and configuration¶
Xadmin Quickstart Guide¶
For using Xadmin, Django 1.4 needs to be installed and an Admin Site has to be activated.
Installation¶
Using pip
:
pip install django-xadmin
Installing from source
Download the latest source tarball from https://github.com/sshwsfc/django-xadmin or git clone
the repository. Then execute the following in the project directory:
pip install -r requirements.txt
Note
Before running you can choose to edit the file requirements.txt
. Note that xlwt
is not required; you can delete this entry if you do not need to export Excel workbooks.
Running the demo¶
If you have downloaded the source tarball of Xadmin, you will be able to locate a demo_app
directory in the project hierarchy. The commands below can be issued to quickly create a demo instance of Xadmin:
cd demo_app
python manage.py runserver
Point your browser to http://127.0.0.1:8000
to see the results.
Working with existing projects¶
Being a Django application, Xadmin can be easily plugged into Django-powered sites.
First, edit your settings.py
to add Xadmin to your INSTALLED_APPS
. (Note that the vanilla Django admin app’s dependencies also have to be installed, but Django admin itself need not):
INSTALLED_APPS = (
...
'xadmin',
'crispy_forms',
'reversion',
...
)
Then add URL patterns and do autodiscover
:
# -*- coding: utf-8 -*-
import xadmin
xadmin.autodiscover()
# version模块自动注册需要版本控制的 Model
from xadmin.plugins import xversion
xversion.register_models()
urlpatterns = patterns('',
url(r'xadmin/', include(xadmin.site.urls)),
)
Collect media:
python manage.py collectstatic
Customization of xadmin¶
Features¶
Features of xadmin¶
Compatibility with stock Django admin¶
Use of Bootstrap as UI framework¶
Flexible and customizable page layout¶
Main page dashboard and widgets¶
Font icons and Model icons¶
Instant editing¶
Charting functionality¶
related information menu¶
Revision management for data¶
Detail views for data¶
Access control for viewing¶
Enhanced filters¶
Bookmarks¶
Data exporting¶
Auto-completion¶
In-line data editing¶
Wizard for inputting data¶
Powerful plugin mechanism¶
Plugins¶
Xadmin plugins¶
plugins overview¶
built-in plugins¶
Action¶
functions¶
Action plugin provides data selection function on the data list page. The selected data can be processed specially after Action. The batch deletion function is provided as default Action.
screenshot¶

use¶
To enable the Action, the developer can set the attribute ‘actions’ of Model OptionClass which is a list type. In default, the xadmin has enabled DeleteSelectedAction which gives you an option to delete selected items from the list view. You can also implement your customized Action class, and please see the following example.
There needs an Action class first, which subclasses BaseActionView. BaseActionView is a subclass of
ModelAdminView
:from xadmin.plugins.actions import BaseActionView class MyAction(BaseActionView): # 这里需要填写三个属性 action_name = "my_action" #: 相当于这个 Action 的唯一标示, 尽量用比较针对性的名字 description = _(u'Test selected %(verbose_name_plural)s') #: 描述, 出现在 Action 菜单中, 可以使用 ``%(verbose_name_plural)s`` 代替 Model 的名字. model_perm = 'change' #: 该 Action 所需权限 # 而后实现 do_action 方法 def do_action(self, queryset): # queryset 是包含了已经选择的数据的 queryset for obj in queryset: # obj 的操作 ... # 返回 HttpResponse return HttpResponse(...)then apply this Action:: on OptionClass in Model
class MyModelAdmin(object): actions = [MyAction, ]then you have completed your Action
data filters¶
functions¶
The list view provides data filtering function and you can search the data by fuzzy searching, numerical range, date range, etc.
screenshot¶

use¶
In Model OptionClass, set up the following attributes:
list_filter
propertyThis property can specify the name of column can be filtered, and then the system will generate a searcher automatically
search_fields
property属性指定可以通过搜索框搜索的数据列的名字, 搜索框搜索使用的是模糊查找的方式, 一般用来搜素名字等字符串字段
free_query_filter
property
True
by default, specifying whether free search is allowed or not. If free search is on, users can perform customized search by passing the argument url. For exampe:http://xxx.com/xadmin/auth/user/?name__contains=tony
Samples that use filters:
class UserAdmin(object):
list_filter = ('is_staff', 'is_superuser', 'is_active')
search_fields = ('username', 'first_name', 'last_name', 'email')
version¶
temporarily unaccessible
create filters¶
You can create your own filters to peform some specific filtering. The filters need to subclass :class: xadmin.filters.BaseFilter. Use :attr: xadmin.filters.manager to register the filters.
chart plugin¶
functions¶
The data chart can be generated from the data listed in the list view page. You can specify a number of data columns to generate more charts.
screenshot¶

use¶
Set the data_charts
property of Model OptionClass a dict. The key is the name of the chart and the value is the specific setting properties. Usage examples:
class RecordAdmin(object):
data_charts = {
"user_count": {'title': u"User Report", "x-field": "date", "y-field": ("user_count", "view_count"), "order": ('date',)},
"avg_count": {'title': u"Avg Report", "x-field": "date", "y-field": ('avg_count',), "order": ('date',)}
}
The main properties of the chart are:
title
: display name of the chartThe ‘x-field’ property represents the data for x axis in the chart, normally it is date or time.
The ‘y-field’ is the y-axis of the data charts, which is a list containing data fields. If the ‘y-field’ list contains more than one field, all these data will be displayed in one chart.
order
: sorting information, if it is not provided, the order of the data list will be used
version¶
temporarily unaccessible
Bookmarks¶
functions¶
It records the results of special processing such as data filtering and ordering. The added bookmarks also can be added as small widget from the dashboard of the Index page.
screenshot¶

use¶
set the following properties in Model OptionClass:
show_bookmarks
property:set the bookmarks function on or not,
True
by default
list_bookmarks
propertySet default bookmarks. Users can add their own bookmarks on the list page. You can also provide some bookmarks in advance. Usage examples:
class UserAdmin(object): list_bookmarks = [{ 'title': "Female", # 书签的名称, 显示在书签菜单中 'query': {'gender': True}, # 过滤参数, 是标准的 queryset 过滤 'order': ('-age'), # 排序参数 'cols': ('first_name', 'age', 'phones'), # 显示的列 'search': 'Tom' # 搜索参数, 指定搜索的内容 }, {...} ]
version¶
temporarily unaccessible
Data exporting¶
functions¶
This plugin provides data exporting function on the data list page. Data can be exported in format Excel, CSV, XML or json.
screenshot¶

use¶
Note
To export the data in Excel format, install xlwt <http://pypi.python.org/pypi/xlwt> first.
In default, the xadmin can export the data file as Excel, CSV, XML and JSON format. The supported export file format can be set by the property ‘list_export’ of OptionClass, which has values xls, cvs, xml and json. Or you can set None to the list_export to disable data export function.
class MyModelAdmin(object):
list_export = ('xls', xml', 'json')
Refresh the list at given intervals.¶
functions¶
This plugin provides refresh function, which is very useful to check a real-time data from a list view page.
screenshot¶

use¶
To enable the refresh function plugin, just simply set up the ‘refresh_times’ property of OptionClass. The ‘refresh_times’ is a list containing the interval. In default, this plugin is inactive. Please see the following example:
class MyModelAdmin(object):
# 这会显示一个下拉列表, 用户可以选择3秒或5秒刷新一次页面.
refresh_times = (3, 5)
Display data details¶
functions¶
This plugin uses Ajax to show the details of the relevant fields in the list view page.
screenshot¶

use¶
To use this plugin, you can set up the properties ‘show_detail_fields’ and ‘show_all_rel_details’ in OptionClass. The property ‘show_detail_fields’ specifies the fields shown in details, and all related fields will shown in details when ‘show_all_rel_details’ is set as True (default setting). Please check the following example:
class MyModelAdmin(object):
show_detail_fields = ['group', 'father', ...]
instant data edit¶
functions¶
Ajax is used by this plugin to modify the value of some field instantly. There is no need for submitting or page refreshing to complete the data modification. It is quiet useful when it comes to some frequently modified field, (for example, state).
screenshot¶

use¶
This plugin can set by the ‘list_editable’ property of OptionClass. The ‘list_editable’ is a tuple used to specify the editable fields in the list view page.
class MyModelAdmin(object):
list_editable = ['price', 'status', ...]
Xadmin 插件制作¶
插件原理¶
Xadmin 的插件系统架构设计一定程度上借鉴了 wordpress
的设计。 想要了解 Xadmin 的插件系统架构首先需要了解 Xadmin AdminView
的概念。
简单来说,就是 Xadmin 系统中每一个页面都是一个 AdminView
对象返回的 HttpResponse
结果。Xadmin 的插件系统做的事情其实就是在 AdminView
运行过程中改变其执行的逻辑, 或是改变其返回的结果,起到修改或增强原有功能的效果。下面让我们看看整个插件从制作完成到实际运行的整个过程。
首先需要创建自己的插件类, 插件类继承 BaseAdminPlugin
class HelloWorldPlugin(BaseAdminPlugin):
...
开发好的插件首先要注册到 Xadmin 中, 示例代码如下:
# ListAdminView 是 Model 列表页面
xadmin.site.register_plugin(HelloWorldPlugin, ListAdminView)
其中插件的注册和使用可以参看 xadmin.sites.AdminSite.register_plugin()
当将插件注册到 Xadmin 后, Xadmin 在创建 AdminView
实例的时候会将该插件放入实例的 plugins
属性。当 AdminView
在处理请求
时,会首先逐个调用 plugins
中插件的 init_request()
方法,插件在该方法中一般进行初始化的操作并且返回一个 Boolean 值告诉 AdminView
是否需要加载该插件。当 init_request()
方法返回值为 False
时, AdminView
不会加载该插件。实例如下:
class HelloWorldPlugin(BaseAdminPlugin):
say_hello = False
# 初始化方法根据 ``say_hello`` 属性值返回
def init_request(self, *args, **kwargs):
return bool(self.say_hello)
在以上实例中,插件根据自身的 say_hello
属性来决定是否让自己被加载。您可能会迷惑, say_hello
属性看起来一直会是 False
呀,那样这个插件不是永远不会被加载?
其实 Xadmin 在创建插件实例的时候会将 OptionClass
的同名属性替换插件的属性。这样,在不同的 OptionClass
下会有不同的插件结果,实例如下:
class SomeModelAdmin(object):
say_hello = True
...
site.register(SomeModel, SomeModelAdmin)
理解以上内容后,让我们再看看插件具体是如何起作用的。在 AdminView
的执行过程中,可以被插件截获或修改的方法使用 filter_hook()
装饰,实例如下:
class ListAdminView(ModelAdminView):
# 可以被插件截获或修改的方法使用该装饰器装饰
@filter_hook
def get_context(self):
...
使用 filter_hook()
装饰的方法执行过程中会根据一定原则执行插件中的同名方法,具体信息查考该装饰器的文档内容。
-
xadmin.views.base.
filter_hook
(func)[source]¶ 表明 AdminView 的方法可以被插件插入的装饰器。执行使用了该装饰器的方法时,会按照以下过程执行:
首先将实例的 plugins 属性取出,取出含有同样方法名的插件
按照插件方法的
priority
属性排序顺序执行插件方法,执行插件方法的规则:
如果插件方法没有参数,AdminView 方法的返回结果不为空则抛出异常
如果插件方法的第一个参数为
__
,则 AdminView 方法将作为第一个参数传入,注意,这时还未执行该方法, 在插件中可以通过__()
执行,这样就可以实现插件在 AdminView 方法执行前实现一些自己的逻辑,例如:def get_context(self, __): c = {'key': 'value'} c.update(__()) return c
如果插件方法的第一个参数不为
__
,则执行 AdminView 方法,将结果作为第一个参数传入
最终将插件顺序执行的结果返回
根据该装饰器的执行原则,如果我们想修改上面示例中 ListAdminView
的 get_context
的返回值,可以在插件中实现如下代码:
class HelloWorldPlugin(BaseAdminPlugin):
# 在插件中加入同名方法,修改 ``ListAdminView`` 的 ``get_context`` 返回的值
def get_context(self, context):
context.update({'hello_target': 'World!!'})
return context
如果我们希望插件在 AdminView
的方法前执行,或是完全使用自己的方法替代 AdminView
的方法可以这样:
class HelloWorldPlugin(BaseAdminPlugin):
# 第一个参数为 ``__`` 。这样 ``__`` 即为 ``ListAdminView`` 的 ``get_context`` 方法本身,注意,这时还没有执行这个方法。
def get_context(self, __):
context = {'hello_target': 'World!!'}
#我们可以在任何时候执行 ``AdminView`` 的方法,或是根本不执行
context.update(__())
return context
至此,加入的插件就实现了对 AdminView
方法的完全控制。
模板插件
我们知道,Django 中一个完整的 View 是包含模板的,模板用来生成 View 最终返回的 HTML 内容。当然,插件也可以在模板中插入自己的内容。我们来看看具体如何实现。
首先让我们来看看 Xadmin 中的模板代码示例片段 (change_list.html):
{% load xadmin %}
...
<form id="changelist-form" action="" method="post"{% view_block 'result_list_form' %}>{% csrf_token %}
{% view_block 'results_top' %}
<div class="results">
{% if results %}
...
其中的 view_block
Tag 即为插件的 插入点 。插件可以在自己的插件类中使用 block_
+ 插入点名称
方法将 HTML 片段插入到页面的这个位置,示例如下:
class HelloWorldPlugin(BaseAdminPlugin):
# context 即为 TemplateContext, nodes 参数包含了其他插件的返回内容。
# 您可以直接返回 HTML 片段,或是将内容加入到 nodes 参数中
def block_results_top(self, context, nodes):
return s"<div class='info'>Hello %s</div>" % context['hello_target']
插件实例¶
下面让我们来看一个 Xadmin 中完整的插件实例:
from django.template import loader
from xadmin.sites import site
from xadmin.views import BaseAdminPlugin, ListAdminView
REFRESH_VAR = '_refresh'
# 该插件实现了一个列表页面刷新器的效果
class RefreshPlugin(BaseAdminPlugin):
# 用户可以定制刷新的频率,可以传入多个值。该属性会被 ``OptionClass`` 的同名属性替换
refresh_times = []
def init_request(self, *args, **kwargs):
# 根据用户是否制定了刷新器来决定是否启动该插件
return bool(self.refresh_times)
# 插件拦截了返回 Media 的方法,加入自己需要的 js 文件。
def get_media(self, media):
if self.request.GET.get(REFRESH_VAR):
# 放页面处于自动刷新状态时,加入自己的 js 制定刷新逻辑
media.add_js([self.static('xadmin/js/refresh.js')])
return media
# Block Views
# 在页面中插入 HTML 片段,显示刷新选项。
def block_top_toolbar(self, context, nodes):
current_refresh = self.request.GET.get(REFRESH_VAR)
context.update({
'has_refresh': bool(current_refresh),
'clean_refresh_url': self.admin_view.get_query_string(remove=(REFRESH_VAR,)),
'current_refresh': current_refresh,
'refresh_times': [{
'time': r,
'url': self.admin_view.get_query_string({REFRESH_VAR: r}),
'selected': str(r) == current_refresh,
} for r in self.refresh_times],
})
# 可以将 HTML 片段加入 nodes 参数中
nodes.append(loader.render_to_string('xadmin/blocks/refresh.html', context_instance=context))
# 注册插件
site.register_plugin(RefreshPlugin, ListAdminView)
最后不要忘记在适当的地方加载该代码, 让其执行。一般情况下,你可以将其写到 adminx.py 文件中,这样,只要您的 APP 加入到 Django Settings 的 INSTALL_APPS 中, Xadmin 就会自动执行 app 下的 adminx.py 文件。
插件开发¶
了解了插件的运行原理后我们就可以开发自己的插件了。首先我们需要了解插件类中的实用方法。因为插件是继承 BaseAdminPlugin
类,而该类继承自
BaseAdminObject
,所以这两个类的方法都可以在插件中使用。
Xadmin 在创建插件时会自动注入以下属性到插件实例中:
- request : Http Request
- user : 当前 User 对象
- args : View 方法的 args 参数
- kwargs : View 方法的 kwargs 参数
- admin_view :
AdminView
实例- admin_site : Xadmin 的
admin_site
对象实例
如果 AdminView
是 ModelAdminView
的子类,还会自动注入以下属性:
- model : Model 对象
- opts : Model 的 _meta 属性
接下来您应该考虑打算制作什么功能的插件了。不同功能的插件额能需要注册到不同的 AdminView
上,Xadmin 系统中
主要的 AdminView
有:
BaseAdminView
: 所有AdminView
的基础类,注册在该 View 上的插件可以影响所有的AdminView
CommAdminView
: 用户已经登陆后显示的 View,也是所有登陆后 View 的基础类。该 View主要作用是创建了 Xadmin 的通用元素,例如:系统菜单,用户信息等。插件可以通过注册该 View 来修改这些信息。ModelAdminView
: 基于 Model 的AdminView
的基础类,注册的插件可以影响所有基于 Model 的 View。ListAdminView
: Model 列表页面 View。ModelFormAdminView
: Model 编辑页面 View。CreateAdminView
: Model 创建页面 View。UpdateAdminView
: Model 修改页面 View。DeleteAdminView
: Model 删除页面 View。DetailAdminView
: Model 详情页面 View。
选择好目标 AdminView
后就要在自己的插件中编写方法来修改或增强这些 AdminView
。其中每个 AdminView
可以
拦截的方法及其介绍请参看各 AdminView
的文档。
插件规范¶
文档模板:
"""
Name
======
作者
----
该插件的作者信息
功能
----
描述插件的主要功能
截图
----
.. image:: /images/plugins/action.png
使用
----
描述插件的使用方法, 以及使用示例.
版本
----
描述插件的版本信息
API
---
.. autoclass:: XXX
"""
API¶
Admin Site¶
-
class
xadmin.sites.
AdminSite
(name='xadmin')[source]¶ The core of xadmin, managing all the register contents of xadmin.
In general there is only one instance of AdminSite within a managed site, and this AdminSite instance is responsible for the following tasks:
register and manage all information required by xadmin
create
admin view class
registered urls in django
xadmin required information includes:
the models need to be managed by xadmin and all information about the admin settings in the models
registered ‘admin view class’
registered ‘model admin view class’
all registered plugins
-
admin_view
(view, cacheable=False)[source]¶ provide Decorator to all Views in the current AdminSite. Use has_permission method of AdminSite to check whether the current user has privilege to access the AdminSite, and redirect to login page if not.
it will be called inside the get_urls method of AdminSite
Parameters: cacheable – 默认情况下,所有的 AdminView 会通过 never_cache
标记成不做缓存,如果确实需要缓存,可以设置 cacheable=True
-
check_dependencies
()[source]¶ check the packages on that the xadmin depends whether are installed correctly.
In default, the ContentType module will be checked to see whether it is installed correctly
-
create_admin_view
(admin_view_class)[source]¶ use the get_view_class method of AdminSite to create AdminView class and return view method which can be called by the get_urls method
Parameters: admin_view_class – AdminView 类
-
create_model_admin_view
(admin_view_class, model, option_class)[source]¶ use get_view_class method of AdminSite to create ModelAdminView and return view method, which can be call by get_urls method
Parameters: - admin_view_class – AdminView 类,该类应该为
ModelAdminView
的子类 - model – Model 类,目前该参数暂无作用
- option_class – Model 的 OptionClass,保存对该 Model 的相关定制
- admin_view_class – AdminView 类,该类应该为
-
get_plugins
(admin_view_class, *option_classes)[source]¶ the core method of xadmin is used to get the plugins from AdminViewClass
to obtain the plugin instances, first find the corresponding plugin classes registered to this AdminView class and all other integrated classes, then apply the OptionClass of the second parameter.
-
get_view_class
(view_class, option_class=None, **opts)[source]¶ the most core method of xadmin is used to create specific AdminViewClass that belongs to xadmin
there are two steps of creating AdminView class instance and dynamically generating the mix class
use the registered OptionClass (see method register), the option_class parameter and the view_class to dynamically create the class instance
retrieve the corresponding plugins according to the view_class and its super classes, and create it as the ‘plugins’ properties of the AdminViewClass
-
has_permission
(request)[source]¶ if return True the request.user at least can access the current xadmin website, otherwise not.
-
register
(model_or_iterable, admin_class=<type 'object'>, **options)[source]¶ register the Model that need to be managed, or register the OptionClass of the AdminView
Parameters: - model_or_iterable – 传入 model 或是指定的 ModelOptionClass
- admin_class – 当 model_or_iterable 为 Model 时,该参数为 ModelAdmin;model_or_iterable 为 AdminView 时 ,该参数为 OptionClass
please see xadmin.views.base.BaseAdminPlugin about the details of Admin Plugin. For example:
from models import SomeModel class SomeModelAdmin(object): pass site.register(SomeModel, SomeModelAdmin)
-
register_modelview
(path, admin_view_class, name)[source]¶ register the classes Model Base Admin View to the AdminSite
Parameters: - path – view对应的url路径
- admin_view_class – 注册的 Model Base Admin View 类
- name – view对应的url name, 要包含两个%%s, 分别会替换为 app_label和module_name
the registered Model Base Admin View in the AdminSite can be used to create AdminView for the registered Model which will contain the relevant Model information. Please check xadmin.views.base.ModelAdminView to see the details. For example:
from xadmin.views import ModelAdminView class TestModelAdminView(ModelAdminView): def get(self, request, obj_id): pass site.register_modelview(r'^(.+)/test/$', TestModelAdminView, name='%s_%s_test')
after the registration, the view can be accessed by path ‘/%(app_label)s/%(module_name)s/123/test’
-
register_plugin
(plugin_class, admin_view_class)[source]¶ register the Plugin class to the instance of AdminSite, the instance of corresponding plugin class which is bound to the current view class will be effective when any instance of the AdminView classes runs
Parameters: - plugin_class – view对应的url路径
- admin_view_class – 该 plugin 绑定的 Admin View 类
please see xadmin.views.base.BaseAdminPlugin about the details of Admin Plugin. For example:
from xadmin.views import BaseAdminPlugin class TestAdminPlugin(BaseAdminPlugin): def get_context(self, context): context['test'] = True return context site.register_plugin(TestAdminPlugin, SomeAdminView)
after the registration, the plugin will be called when the get_context method of SomeAdminView is invoked
-
register_view
(path, admin_view_class, name)[source]¶ an independent admin page e.g. login page, introduction page, help page, ect can be created by registering the AdminView class to the AdminSite.
Parameters: - path – view对应的url路径
- admin_view_class – 注册的 Admin View 类
- name – view对应的url name
See xadmin.views.base.BaseAdminView to see the details about AdminView. For example:
from xadmin.views import BaseAdminView class TestAdminView(BaseAdminView): def get(self, request): pass site.register_view(r'test_view/$', TestModelAdminView, name='for_test')
after the registration, the users can access the view through the path of ‘/test_view/’
-
unregister
(model_or_iterable)[source]¶ unregister the Model or OptionClass
if the Model or OptionClass have never been registered, it throws exception of ‘xadmin.sites.NotRegistered’
-
urls
¶ return the urls attribute of the xdmin site, which is used to set django urls. This is property getter method and can be found in the ‘urls.py’ file of Django framework, the example shown as the following:
from django.conf.urls import patterns, include, url import xadmin xadmin.autodiscover() urlpatterns = patterns('', url(r'', include(xadmin.site.urls)), )
-
exception
xadmin.sites.
AlreadyRegistered
[source]¶ if a model has been registered to AdminSite, an exception will be thrown when register it again.
Views¶
-
class
xadmin.views.
BaseAdminObject
[source]¶ The base parent class of
BaseAdminView
andBaseAdminPlugin
, support some comm method.-
get_admin_url
(name, *args, **kwargs)[source]¶ a shortcut method to get the url by the name parameter, the url namespace of AdminSite.app_name will be appended
-
get_form_params
(new_params=None, remove=None)[source]¶ add or delete a parameter to/from the current request, and generate the hidden input. This method is used to render the parameter with the form
Parameters: - new_params – 要新加的参数,该参数为 dict
- remove – 要删除的参数,该参数为 list, tuple
-
get_model_perm
(model, name)[source]¶ this method is used to get the permission of a specified Model, see the following example:
>>> view.get_model_perm(User, 'view') >>> 'auth.user_view'
-
get_model_url
(model, name, *args, **kwargs)[source]¶ a shortcut method, used to get the url by given model and name parameter, the urlname will be generated automatically and with the namespace of AdminSite.app_name.
-
get_model_view
(view_class, model, *args, **kwargs)[source]¶ get the instance of MOdelAdminViewClass. First get the corresponding model OptionClass through AdminSite, then call get_view method.
Parameters: - view_class – ModelAdminViewClass 的类
- model – 绑定的 Model 类
-
get_query_string
(new_params=None, remove=None)[source]¶ generate new query string basing on the original
Parameters: - new_params – 要新加的参数,该参数为 dict
- remove – 要删除的参数,该参数为 list, tuple
-
get_view
(view_class, option_class=None, *args, **kwargs)[source]¶ get the instance of AdminViewClass. In fact it works by calling xadmin.sites.AdminSite.get_view_class method.
Parameters: - view_class – AdminViewClass 的类
- option_class – 希望与 AdminViewClass 合并的 OptionClass
-
has_model_perm
(model, name, user=None)[source]¶ check whether the current user has a certain permission of some Model, for example:
>>> view.has_model_perm(User, 'view') >>> True
-
message_user
(message, level='info')[source]¶ Send a message to the user. The default implementation posts a message using the django.contrib.messages backend.
-
render_response
(content, response_type='json')[source]¶ it is a shortcut method to create an instance of HttpResponse. If the response_type is set as ‘json’, the result will be convert to json format and then output.
-
-
class
xadmin.views.
BaseAdminPlugin
(admin_view)[source]¶ It is the base class of all Plugin classes, inherited from BaseAdminObject class. Please see xadmin.sites.AdminSite.register_plugin method to check the Plugin registration and usage. Refer to the method fliter_hook about the Plugin principle.
-
filter_hook
(func)¶ the methods of AdminView with this decorator can be extended by Plugin classes, and will be executed as the following procedure:
get the plugins property from the instance then retrieve the plugin with the same method name
order by the ‘priority’ of the plugins
execute the plugin methods in order and follow the rules:
if no parameters are given to the plugin method, the return of AdminView method is not null and throws exception.
If the first parameter passed to the plugin method is ‘__’ then this parameter is the AdminView method. The plugin method will be executed through calling ‘__()’ and before the AdminView method.
def get_context(self, __): c = {'key': 'value'} c.update(__()) return c
If the first parameter of the plugin method is not ‘__’, the AdminView method will be executed and it’s return value will be passed as the first parameter.
In final the plugins are executed sequentially and the results are returned in order.
-
init_request
(*args, **kwargs)[source]¶ This is the initialization method of plugin class, which is the first invoked method after creating the plugin. Through this method, the plugin required attributes are initialized and check whether the current request needs to load this plugin instance. For example the implementation of Ajax plugin.
def init_request(self, *args, **kwargs): return bool(self.request.is_ajax() or self.request.REQUEST.get('_ajax'))
if the return value is ‘False’, the corresponding AdminView instance will not load the pulgin
-
-
class
xadmin.views.
BaseAdminView
(request, *args, **kwargs)[source]¶ This is the base class of all AdminView classes which is inherited from BaseAdminObject and django.views.generic.View.
the core class of Xadmin framework, all AdminView classes need to inherit from this class. The most obvious difference between Xadmin and Django Admin is that every request will cause an instance of AdminView class be created which also is Class-based View implemented in Django 1.3, see Django official document Class-based generic views <https://docs.djangoproject.com/en/1.4/topics/class-based-views/>
The Class-based view has many advantages. First, every time a request coming, an new instance with variables related to the current request is created to response, this is useful when extend the class or override the super class method.
Second, Class-based View is easy to implement a plugin function and dynamically loading plugin because every instance of AdminView need to load specific plugins according to its circumstance, see BaseAdminPlugin class about the details.
It is very simple to implement a customized AdminView class, for instance:
from xadmin.sites import site from xadmin.views import BaseAdminView class MyAdminView(BaseAdminView): def get(self, request, *args, **kwargs): pass site.register_view(r'^me_test/$', MyAdminView, name='my_test')
By this you can access this view by me_test/. Meanwhile Xadmin offers some common AdminView classes and they are:
CommAdminView class, which is the basic view of general user interface, provides the data required by Xadmin general user interface (such as menu).
ModelAdminView class, one of the core classes, provide the Model-based AdminView classes.
-
classmethod
as_view
()[source]¶ this overrides View.as_view method and integrates the View.dispatch method inside. Some initialization work is moved and completed by the initi method of AdminView class, please see ‘BaseAdminView.init_request’
-
get_context
(*args, **kwargs)[source]¶ filter_hook
return the required context object to display the requested page.
-
get_media
(*args, **kwargs)[source]¶ filter_hook
retrieve the required Media object to generate css and js files.
-
init_plugin
(*args, **kwargs)[source]¶ this is the plugin initialization method of AdminView class, which is called after BaseAdminView.init_request method execution. All plugins from the base_plugins attribute are instantiated in order and loaded according to the result of BaseAdminPlugin.init_request method. If the plugin is required it will be kept by the plugins attribute.
-
class
xadmin.views.
CommAdminView
(request, *args, **kwargs)[source]¶ this is a generic AdminView class extending BaseAdminView. The global settings of Xadmin website can be done by this class, which are
Title of website
Global icon for model
Menu of website
** View property **
filter_hook
-
get_context
(*args, **kwargs)[source]¶ filter_hook
Context params:
site_title: assign a string value to this attribute to set the title of the site, the default value is “Django Xadmin”
nav_menu: it keeps the system menu items after processing the user’s permission. This attribute will be cached in SESSION if under non DEBUG mode.
-
get_model_icon
(*args, **kwargs)[source]¶ filter_hook
It is used to get the icon of Model class, which actually is css class. The generated HTML is shown as the following:
<i class="icon-model icon-{{model_icon}}"></i>
This example applies the stand format of Bootstrap icon. For now Xadmin uses Font Icon (Font-Awesome), you can customized your icons, you can refer to http://fortawesome.github.com/Font-Awesome/#contribute to create a customized font and icon
Note
The Model icons are used by the following places, and also you can use within your customized pages.
system menu
in the title of list page
in the title of creating, updating and deleting page
FAQ: if define Model icons
A global Model icon can be set by the property ‘globe_models_icon’ in the OptionClass of CommAdminView class. Or set the property ‘model_icon’ in the OptionClass of Models.
filter_hook
this method returns the website menu. If get_site_menu method return not none, the return value will be token as the first part the menu, and Xadmin appends the Model listing menu items as the rest part the menu. If None is returned by get_site_menu method, Xadmin will automatically generate two levels of menu according to App and Model.
Return type: 格式见 get_site_menu()
返回格式
FAQ: how to customized system menu
a method for the derived class to override and implement customized website menu. It can be overwritten via child class or OptionClass.
({ "title": "菜单标题", "perm": "权限标示", "icon": "图标的 css class", "url": "菜单url", "menus": [...] # 子菜单项 })
the values of ‘perm’ and ‘url’ in the menu can be provide by the shortcut methods BaseAdminObject.get_model_perm and BaseAdminObject.get_model_url if base on Model. For example:
class AdminSettings(object): def get_site_menu(self): return ( {'title': '内容管理', 'perm': self.get_model_perm(Article, 'change'), 'menus':( {'title': '游戏资料', 'icon': 'info-sign', 'url': self.get_model_url(Article, 'changelist') + '?_rel_categories__id__exact=2'}, {'title': '网站文章', 'icon': 'file', 'url': self.get_model_url(Article, 'changelist') + '?_rel_categories__id__exact=1'}, )}, {'title': '分类管理', 'perm': self.get_model_perm(Category, 'change'), 'menus':( {'title': '主要分类', 'url': self.get_model_url(Category, 'changelist') + '?_p_parent__isnull=True'}, {'title': '游戏资料', 'url': self.get_model_url(Category, 'changelist') + '?_rel_parent__id__exact=2'}, )}, ) site.register(CommAdminView, AdminSettings)
-
class
xadmin.views.
ModelAdminView
(request, *args, **kwargs)[source]¶ this is a Model-based AdminView class. The AdminSite instance will automatically create a url to the class extending ModelAdminView for each registered Model class. The registration is completed by calling the register_modelview method of AdminSite instance. To see the details please refer to the method API document, or see the following example:
from xadmin.views import ModelAdminView class TestModelAdminView(ModelAdminView): def get(self, request, obj_id): pass site.register_modelview(r'^(.+)/test/$', TestModelAdminView, name='%s_%s_test')
the user can access this view by path /%(app_label)s/%(module_name)s/123/test after it is registered.
Option properties
-
fields
= None¶ list or tuple type, it defines the fields will be displayed
-
exclude
= None¶ list or tuple type, it defines the fields will be excluded from the editing page
-
ordering
= None¶ it is a dict type, the default order for the reterieved Model queryset.
-
model
= None¶ a bounded Model class, which is automatically assigned to OptionClass when register the Model class, see the regsiter method of AdminSite class
instance property
filter_hook
-
get_context
(*args, **kwargs)[source]¶ filter_hook
Context params:
opts: the _meta attribute of Model class
app_label: the app_label attribute of Model class
module_name: the module_name attribute of Model class
verbose_name: the verbose_name of Model class
-
get_model_perms
()[source]¶ return a dict containing all permissions, which has key values: add, view, change, delete with boolean values indicating whether the current user has the corresponding permission.
-
get_object
(*args, **kwargs)[source]¶ filter_hook
get the unique instance of Model through object_id. If the Model instance does not exist return None.
-
get_ordering
()[source]¶ return the ordering of the Model list. The default return value is ModelAdminView.ordering, which can be overridden by the subclass.
-
get_template_list
(template_name)[source]¶ return a list of templates according to template_name. The created page is one of these templates and you can easily override this method to get the customized template. The list format is shown as the following:
"xadmin/%s/%s/%s" % (opts.app_label, opts.object_name.lower(), template_name), "xadmin/%s/%s" % (opts.app_label, template_name), "xadmin/%s" % template_name,
-
has_view_permission
(obj=None)[source]¶ return whether the current user has the view right
Note
in the current version, if a user has the updating right then also own the view right. This default can be changed with your customized subclass
-
-
class
xadmin.views.
ListAdminView
(request, *args, **kwargs)[source]¶ this is the data list AdminView class, which implements the data sorting and paging functions.
Option properties
-
list_display
= ('__str__',)¶ the default field list to display
-
list_display_links
= ()¶ the list of links to display data in details which are editable
the setting of whether load the related data in advance, using select_related
-
list_per_page
= 50¶ the number of data records displayed in each page.
-
list_max_show_all
= 200¶ the maximum number of data records displayed in each page.
-
list_exclude
= ()¶ the list of fields excluded from displaying, this list contains the fields that are not be displayed in the page.
-
search_fields
= ()¶ search data with fields keywords listed by this attribute.
-
ordering
= None¶ the default data order
-
object_list_template
= None¶ define the template used to display data
-
get_context
(*args, **kwargs)[source]¶ filter_hook
Context params:
‘model_fields’ defines the list information that can be displayed, which is used for ‘select list to show’ function
result_headers contains the head information of list table, is the instance of ResultHeader class
‘results’: the cells in each row of the table, which is the instance object of ResultItem class
-
get_list_display
(*args, **kwargs)[source]¶ filter_hook
obtain the columns to display. If the request contains ‘_cols’ parameter then use ‘_cols’, otherwise use ‘list_display’ attribute
Note
this method only save the value of list_display with the ‘base_list_display’ attribute. If some plugin (e.g. Action plugin) add extra values to this method returned value, the number of displayed column increases but the added data is not effective to other plugins (e.g. the export plugin). This keeps the original data of displayed column separated, which can be retrieved from ‘base_list_display’.
-
get_list_display_links
(*args, **kwargs)[source]¶ filter_hook
return a group of column displayed as links to editing page (if the current user has editing permission) or to view page. In default, the attribute of ‘list_display_links’ is used for this function if it is not None, or make the first item in list_display attribute as a link.
-
get_list_queryset
(*args, **kwargs)[source]¶ filter_hook
obtain the Model’s queryset that is sorted and filtered, and other plugins can modify this queryset.
-
get_media
(*args, **kwargs)[source]¶ filter_hook
return the Media object, and ListAdminView employs ‘xadmin.page.list.js’ javascript file
-
get_model_method_fields
()[source]¶ make and display a column with the returned value from methods in OptionClass which has True for is_column attribute. Those methods are wrapped by FakeMethodField and the displayed values are turned to fake database fields.
-
get_ordering
(*args, **kwargs)[source]¶ filter_hook
Returns the list of ordering fields for the change list. First we check the get_ordering() method in model admin, then we check the object’s default ordering. Then, any manually-specified ordering from the query string overrides anything. Finally, a deterministic order is guaranteed by ensuring the primary key is used as the last ordering field.
-
get_ordering_field
(*args, **kwargs)[source]¶ filter_hook
obtain the field names need to be sorted from the ‘field_name’ parameter which can be a standard database field or callable or one Model attribute of OptionClass. In this case, the ‘admin_order_field’ attribute is taken for sorting. If no value of ‘admin_order_field’ is given return None.
class UserAdmin(object): def my_field(self, obj): return obj.name.lower() my_field.admin_order_field = 'name'
-
get_ordering_field_columns
(*args, **kwargs)[source]¶ filter_hook
Returns a SortedDict of ordering field column numbers and asc/desc
-
get_page_number
(*args, **kwargs)[source]¶ filter_hook
return the html code of pagination component, bootstrap is applied in default.
Parameters: i – 页码, 可能是 DOT
-
get_paginator
(*args, **kwargs)[source]¶ filter_hook
use paginator_class to instantiate a paginator object and return it.
-
get_response
(*args, **kwargs)[source]¶ filter_hook
in default this method has no return value after executing ‘get_context’ method, but plugins can override it and return specified HttpResponse object.
-
init_request
(*args, **kwargs)[source]¶ initialize the request and check whether the current user has view permission, then do initializing the variables required by generating data for the list view.
-
make_result_list
()[source]¶ make data and pagination for the list view, the displayed data is assigned to ‘result_list’ arrtibute. Plugins can process the generated data after this method.
-
post
(*args, **kwargs)[source]¶ filter_hook
process the POST request of Model list view and return the same result with GET request in default. Plugins can override ‘post_response’ method to change the return value for POST request.
-
post_response
(*args, **kwargs)[source]¶ filter_hook
this method can be used to process the response to POST request, it returns None in default. Plugins can override it and return specified HttpResponse.
-
result_header
(*args, **kwargs)[source]¶ filter_hook
return a column header information of the table in list view, which is an instance of ResultHeader class.
Parameters: - field_name – 列的名字
- row –
ResultHeader
实例
-
result_headers
(*args, **kwargs)[source]¶ filter_hook
return the header information of the table in list view, which is an instance of ‘ResultRow’ class. The column information is kept by ‘cells’ attribute of ‘ResultRow’ class
-
result_item
(*args, **kwargs)[source]¶ filter_hook
return a field value of a Model object record, which is a ‘ResultItem’ instance.
Parameters: - obj – Model 对象
- field_name – 列的名字
- row –
ResultHeader
实例
-
result_row
(*args, **kwargs)[source]¶ filter_hook
return a row with model instance data to display, which is actually instance of ‘ResultRow’ class. The ‘cells’ attribute of ‘ResultRow’ contains the detail information for all columns.
Parameters: obj – Model 对象
-
-
class
xadmin.views.
ModelFormAdminView
(request, *args, **kwargs)[source]¶ this AdminView class is a base class used to create or update data basing on a model form. It provides functions such as displaying and updating data through form. Class ‘CreateAdminView’ and ‘UpdateAdminView’ inherit from this class.
Option properties
-
form
= <class 'django.forms.models.ModelForm'>¶ refers to the Form class used to generate form object basing on Model class, it is django.forms.ModelForm by default.
-
formfield_overrides
= {}¶ specify a Form Field class to override the Model Field, for example:
class AtricleAdmin(object): formfield_overrides = { models.FileField:{'widget': mywidgets.XFileWidget}, }
by this, mywidgets.XFileWidget is used to display all FileField defined in the model class.
-
readonly_fields
= ()¶ specifies read-only fields which can not be edited.
-
style_fields
= {}¶ specifies the Style for a given Field. Style can make different display effects for one field type. For instance, radio button has common and inline Style values. Xadmin will implement more Field Style for form plugins. You can apply a certain style by setting a defined Style value.
class AtricleAdmin(object): style_fields = {"content": "rich-textarea"}
rich-textarea is Style value provided by some plugin class, thus the ‘content’ will displayed by this plugin style.
-
relfield_style
= None¶ if the model is referred by some other models, this referred model will apply the value of relfield_style as the Field Style to display in other models.
-
save_as
= False¶ whether display ‘Save as’ button.
-
save_on_top
= False¶ whether display a group of button on the top of the page.
-
add_form_template
= None¶ the template page for adding model.
-
change_form_template
= None¶ the template page for updating model.
-
form_layout
= None¶ this is the object of form Layout, which is also a standard object of Crispy Form Layout. Using Layout can easily define the structure of the page. Please refer to Crispy Form document http://django-crispy-forms.readthedocs.org/en/latest/layouts.html to see details. Here is an example of form_layout:
from xadmin.layout import Main, Side, Fieldset, Row, AppendedText class AtricleAdmin(object): form_layout = ( Main( Fieldset('Comm data', 'title', 'category' ), Inline(Log), Fieldset('Details', 'short_title', Row(AppendedText('file_size', 'MB'), 'author'), 'content' ), ), Side( Fieldset('Status', 'status', ), ) )
please check the document of ‘form_layout’ about the elements information of Layout.
-
formfield_for_dbfield
(*args, **kwargs)[source]¶ filter_hook
a callback method during the process of generating form instance, returns instance of Form Field.
Parameters: db_field – Model 的 DB Field
-
get
(*args, **kwargs)[source]¶ filter_hook
display the form, the detail procedure is shown as the following:
call ‘perpare_form’ method
call ‘instance_forms’ method
2.1 call ‘get_form_datas’ method
call ‘setup_forms’ method
call ‘get_response’ method
-
get_context
(*args, **kwargs)[source]¶ filter_hook
Context Params:
‘form’: a Form object
‘original’: the original data object for updating
show_delete: whether display the deleted items
‘add’: whether this is adding data
‘change’: whether this is updating data
‘errors’: the form error messages
-
get_field_attrs
(*args, **kwargs)[source]¶ filter_hook
return a dict containing the Form Field attributes according to the model Field attributes
Parameters: db_field – Model 的 DB Field
-
get_field_style
(*args, **kwargs)[source]¶ filter_hook
return the Form Field attributes according to the Field Style. This method can be filtered out by plugins and provide different Styles.
Parameters: - db_field – Model 的 DB Field
- style – 配置的 Field Style,该值来自于属性
style_fields
-
get_form_helper
(*args, **kwargs)[source]¶ filter_hook
obtain the instance of FormHelper required by the Crispy Form. The details can be found with Crisp Form document
-
get_form_layout
(*args, **kwargs)[source]¶ filter_hook
return the Form Layout object. If the form_layout attribute is set then return it, otherwise return the automatically generated Form Layout object. More Form Layout information can see Crispy Form document. Setting customized Form Layout object is more flexible way to render every element of form.
-
get_model_form
(*args, **kwargs)[source]¶ filter_hook
return ModelForm object which is used to display the form.
-
get_readonly_fields
(*args, **kwargs)[source]¶ filter_hook
return the read-only fields, the derived classes or OPtionClass can override this method.
-
instance_forms
(*args, **kwargs)[source]¶ filter_hook
instantiate the Form object with the return value of ‘get_form_datas’ method, and then keep this Form object with ‘form_obj’ attribute.
-
post
(*args, **kwargs)[source]¶ filter_hook
save form data. The detail procedure is executed as the following:
call ‘perpare_form’ method
call ‘instance_forms’ method
2.1 call ‘get_form_datas’ method
call ‘setup_forms’ method
‘valid_forms’ method
4.1 call ‘save_forms’ method
4.2 call ‘save_models’ method
4.3 call ‘save_related’ method
4.4 call ‘post_response’ method
-
prepare_form
(*args, **kwargs)[source]¶ filter_hook
prepare the Form class through call method ‘get_model_form’, then assign to ‘model_form’ attribute
-
save_forms
(*args, **kwargs)[source]¶ filter_hook
save the form object to ‘new_obj’ attribute, note that this model object has not been saved to database nor pk is generated.
-
save_models
(*args, **kwargs)[source]¶ filter_hook
save the data to the corresponding table in the database.
filter_hook
save the related data.
-
-
class
xadmin.views.
CreateAdminView
(request, *args, **kwargs)[source]¶ this Model AdminView is used to create a model object which inherits from ModelFormAdminView class.
filter_hook
-
class
xadmin.views.
UpdateAdminView
(request, *args, **kwargs)[source]¶ this Model AdminView class is for updating model object, which inherits from ModelFormAdminView class.
filter_hook
-
class
xadmin.views.
DeleteAdminView
(request, *args, **kwargs)[source]¶ the Model AdminView used to delete model object.
Option attributes
-
delete_confirmation_template
= None¶ the template page for confirming deletion
instance property
-
obj
¶ the model object that will be deleted
filter_hook
-
get_context
(*args, **kwargs)[source]¶ filter_hook
Context Params:
title
: 确认删除的标题,如果您没有权限删除的话,会提示无法删除‘object’: the object that will be deleted
deleted_objects
: 关联被删除的所有数据对象‘perms_lacking’: the missing permissions
‘protected’: the protected data, the data can not be deleted.
-
init_request
(object_id, *args, **kwargs)[source]¶ do initialization. Retrieve the object that will be deleted by the keyword of ‘object_id’ and check whether the current user has the required permission.
-
post_response
(*args, **kwargs)[source]¶ filter_hook
the process after successfully deleting. First message the user about the result then redirect to corresponding view according to the user’s permission. If the user has view permission then redirected page is view page, otherwise go to the index page.
-
-
class
xadmin.views.
DetailAdminView
(request, *args, **kwargs)[source]¶ the mode AdminView class that shows the details of model. The view page is only for view data. The view layout is the same with class:`xadmin.views.edit.ModelFormAdminView
Option attributes
-
detail_layout
= None¶ the Layout object of the detail page is a standard Crispy Form Layout object. The advantage of using Layout is that page layout can be well organized.
-
detail_show_all
= True¶ whether display all fields, and the default value is ‘True’. If this is set as ‘True’, those fields not set with the layout object will be displayed, otherwise hide them.
-
detail_template
= None¶ the template of the detail view page.
instance property
-
obj
¶ the model object that will be deleted
filter_hook
-
get_context
(*args, **kwargs)[source]¶ filter_hook
Context params:
‘form’: the form object used to display model object data.
‘object’: the Model object that will be dispalyed
-
get_field_result
(*args, **kwargs)[source]¶ filter_hook
return the instance of ResultField class which contains the field content.
-
get_form_helper
(*args, **kwargs)[source]¶ filter_hook
obtain the instance of FormHelper required by the Crispy Form. The details can be found with Crisp Form document
-
get_form_layout
(*args, **kwargs)[source]¶ filter_hook
return the Form Layout object, if the attribute ‘detail_layout’ is set then return it, or return the automatically generated Form Layout object. More Form Layout information can see Crispy Form document. Setting customized Form Layout object is more flexible way to render every element of form.
-
get_media
(*args, **kwargs)[source]¶ filter_hook
return the Media object of the current view instance, which contains information of ‘form.css’ file.
-
get_model_form
(*args, **kwargs)[source]¶ filter_hook
return ModelForm object which is used to display the form.
-
-
xadmin.views.
filter_hook
(func)[source]¶ the methods of AdminView with this decorator can be extended by Plugin classes, and will be executed as the following procedure:
get the plugins property from the instance then retrieve the plugin with the same method name
order by the ‘priority’ of the plugins
execute the plugin methods in order and follow the rules:
if no parameters are given to the plugin method, the return of AdminView method is not null and throws exception.
If the first parameter passed to the plugin method is ‘__’ then this parameter is the AdminView method. The plugin method will be executed through calling ‘__()’ and before the AdminView method.
def get_context(self, __): c = {'key': 'value'} c.update(__()) return c
If the first parameter of the plugin method is not ‘__’, the AdminView method will be executed and it’s return value will be passed as the first parameter.
In final the plugins are executed sequentially and the results are returned in order.
-
xadmin.views.
csrf_protect_m
(func)¶ This decorator adds CSRF protection in exactly the same way as CsrfViewMiddleware, but it can be used on a per view basis. Using both, or using the decorator multiple times, is harmless and efficient.