官方文档:https://docs.djangoproject.com/en/2.1/ref/contrib/admin/
Overview
If you’re not using the default project template, here are the requirements:
- Add
'django.contrib.admin'
and its dependencies -django.contrib.auth
,django.contrib.contenttypes
,django.contrib.messages
, anddjango.contrib.sessions
- to yourINSTALLED_APPS
setting. - Configure a
DjangoTemplates
backend in yourTEMPLATES
setting withdjango.contrib.auth.context_processors.auth
anddjango.contrib.messages.context_processors.messages
in the'context_processors'
option ofOPTIONS
. - If you’ve customized the
MIDDLEWARE
setting,django.contrib.auth.middleware.AuthenticationMiddleware
anddjango.contrib.messages.middleware.MessageMiddleware
must be included. - Hook the admin’s URLs into your URLconf.
If you need to create a user to login with, use the createsuperuser
command. By default, logging in to the admin requires that the user has the is_superuser
or is_staff
attribute set to True
.
所以,除超级用户外,设置一下属性即可允许一个普通用户登录 admin
后台管理界面:
|
|
Finally, determine which of your application’s models should be editable in the admin interface. For each of those models, register them with the admin as described in ModelAdmin
.(即需要通过 ModelAdmin
注册可以在 admin-site
中修改的表单)
Other topics:
ModelAdmin
Usage
The ModelAdmin
class is the representation of a model in the admin interface. Usually, these are stored in a file named admin.py
in your application. Let’s take a look at a very simple example of the ModelAdmin
:
|
|
当然你也可以不显示地声明一个 ModelAdmin
,这时,Django 将会使用默认的借口做为函数的参数:
|
|
register decorator
There is also a decorator for registering your ModelAdmin
classes:
|
|
It’s given one or more model classes to register with the ModelAdmin
. If you’re using a custom AdminSite
, pass it using the site
keyword argument:
|
|
Discovery of admin files
没看懂,算了。
ModelAdmin
options
The ModelAdmin
is very flexible. It has several options for dealing with customizing the interface. All options are defined on the ModelAdmin
subclass:
ModelAdmin.actions
:可以在 admin-site 页面的下拉列表中,定义自己的actions
函数。详见:AdminActionModelAdmin.actions_on_top
、ModelAdmin.actions_on_bottom
:控制下拉列表在 admin-site 页面中存在的位置。ModelAdmin.actions_selection_counter
:控制是否在动作下拉栏里面显示选择计数器。
(还有很多)
ModelAdmin
methods
…
Adding custom validation to admin
InlineModelAdmin
Usage
Important class:
class
InlineModelAdmin
class
TabularInline
class
StackedInline
The admin interface has the ability to edit models on the same page as a parent model. These are called inlines.
Suppose you have these two models:
|
|
You can edit the books authored by an author on the author page. You add inlines to a model by specifying them in a ModelAdmin.inlines
:
|
|
Django provides two subclasses of InlineModelAdmin
and they are:
The difference between these two is merely the template used to render them.
InlineModelAdmin
options
InlineModelAdmin
shares many of the same features as ModelAdmin
, and adds some of its own (the shared features are actually defined in theBaseModelAdmin
superclass).