阅读:2770次   评论:0条   更新时间:2011-06-01    

Customize the admin form

定制管理表单

 

Take a few minutes to marvel at all the code you didn't have to write. When you call admin.site.register(Poll), Django just lets you edit the object and "guess" at how to display it within the admin. Often you'll want to control how the admin looks and works. You'll do this by telling Django about the options you want when you register the object.

感叹一下吧,你不用写多少代码就能有个管理后台了。当你调用admin.site.register(Poll)时,Django让你可以编辑它的内容,并能够“猜测”怎样展示这个对象。你常常要考虑管理界面的界面和功能,只需要在注册对象的时候告诉Django对应的设置就可以了。

 

Let's see how this works by reordering the fields on the edit form. Replace the admin.site.register(Poll) line with:

我们来看看怎样在编辑表单上给字段重新排序。把admin.site.register(Poll)这一行做如下的替换:

class PollAdmin(admin.ModelAdmin):

    fields = ['pub_date', 'question']

 

admin.site.register(Poll, PollAdmin)

 

You'll follow this pattern -- create a model admin object, then pass it as the second argument to admin.site.register() -- any time you need to change the admin options for an object.

你要遵循这种规范——创建一个管理模型对象,把它作为admin.site.register()的第二个参数传入——当你要改变这个对象的管理设置时。

 

This particular change above makes the "Publication date" come before the "Question" field:

刚才的改变让“Publication date”字段排在了“Question”字段前面:

 

 

 

This isn't impressive with only two fields, but for admin forms with dozens of fields, choosing an intuitive order is an important usability detail.

这对于只有两个字段的模型来说,给你的体验不会太深,但是在一个有很多字段的管理表单里,选择一个直观的排序方式是非常重要的细节。

 

And speaking of forms with dozens of fields, you might want to split the form up into fieldsets:

刚才提到了多字段的表单,你可能想把这些字段都分成一个个组里去,下面的代码可以做到:

class PollAdmin(admin.ModelAdmin):

    fieldsets = [

        (None,               {'fields': ['question']}),

        ('Date information', {'fields': ['pub_date']}),

    ]

 

admin.site.register(Poll, PollAdmin)

 

The first element of each tuple in fieldsets is the title of the fieldset. Here's what our form looks like now:

fieldsets中每个元组的第一个元素就是组的标题。现在我们的表单看起来就像是这样的:

 

 

 

You can assign arbitrary HTML classes to each fieldset. Django provides a "collapse" class that displays a particular fieldset initially collapsed. This is useful when you have a long form that contains a number of fields that aren't commonly used:

你可以给每个组加上HTML样式。Django提供了“collapse”样式,使用这个样式的组初始时是收缩的。当你的表单中有个组包含了很多不常用的字段时,这个样式是很有用的:

class PollAdmin(admin.ModelAdmin):

    fieldsets = [

        (None,               {'fields': ['question']}),

        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),

    ]

 

 

Adding related objects

添加关系对象

 

OK, we have our Poll admin page. But a Poll has multiple Choices, and the admin page doesn't display choices.

Yet.

There are two ways to solve this problem. The first register Choice with the admin just as we did with Poll. That's easy:

现在我们就有了Poll的管理页面了。但是Poll对应的是多个Choice,而管理页面里并没有显示Choice。我们有两种方法来解决这个问题。第一种就想刚才我们注册Poll的管理功能一样,很容易就能实现:

from mysite.polls.models import Choice

 

admin.site.register(Choice)

 

Now "Choices" is an available option in the Django admin. The "Add choice" form looks like this:

现在Django管理后台中“Choices”也出现了。“Add choice”表单看起来就像下面这样:

 

 

 

In that form, the "Poll" field is a select box containing every poll in the database. Django knows that a ForeignKey should be represented in the admin as a <select> box. In our case, only one poll exists at this point.

在这个表单中,“Poll”字段对应一个包含数据库内所有投票记录的选择框。Django知道在管理界面中应该用选择框来表示外键关系。在我们的案例中,这里只会有一个投票。

 

Also note the "Add Another" link next to "Poll." Every object with a ForeignKey relationship to another gets this for free. When you click "Add Another," you'll get a popup window with the "Add poll" form. If you add a poll in that window and click "Save," Django will save the poll to the database and dynamically add it as the selected choice on the "Add choice" form you're looking at.

注意一下“Poll”旁边的“Add Another”链接。每个有外键关系的对象都会有这个链接。点击“Add Another”,会有一个“Add poll”的弹出窗口显示。当你添加数据点击“Save”后,Django会向数据库添加一条新纪录,并将刚才添加的纪录加入到“Add choice”选择框中。

 

But, really, this is an inefficient way of adding Choice objects to the system. It'd be better if you could add a bunch of Choices directly when you create the Poll object. Let's make that happen.

但是,这实在不是一个有效地添加Choice纪录的方法。如果在添加Poll记录的时候能够直接添加批量的Choice纪录是更好的方式。

 

Remove the register() call for the Choice model. Then, edit the Poll registration code to read:

移除掉Choice模型的register()方法调用,然后修改Poll的管理模型的代码:

class ChoiceInline(admin.StackedInline):

    model = Choice

    extra = 3

 

class PollAdmin(admin.ModelAdmin):

    fieldsets = [

        (None,               {'fields': ['question']}),

        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),

    ]

    inlines = [ChoiceInline]

 

admin.site.register(Poll, PollAdmin)

 

This tells Django: "Choice objects are edited on the Poll admin page. By default, provide enough fields for 3 choices."

上面的代码告诉Django:“在Poll的管理界面编辑Choice,预留3Choice的空位。”

 

Load the "Add poll" page to see how that looks:

现在重新加载“Add poll”页面来看看:



  

It works like this: There are three slots for related Choices -- as specified by extra -- and each time you come back to the "Change" page for an already-created object, you get another three extra slots.

现在管理页面上多了3Choice的输入框——这是有extra字段定制的——当你在“Change”页面修改一个已经存在的数据时,除了已有的Choice之外,也有3个输入框。

 

One small problem, though. It takes a lot of screen space to display all the fields for entering related Choice objects. For that reason, Django offers a tabular way of displaying inline related objects; you just need to change the ChoiceInline declaration to read:

但是还有一个小问题。Choice输入框占用的空间太大了。Django还有一种以表格形式显示的方法,你只需要把ChoiceInline做一下修改就可以了:

class ChoiceInline(admin.TabularInline):

    #...

 

With that TabularInline (instead of StackedInline), the related objects are displayed in a more compact, table-based format:

ChoiceInline改成继承自TabularInline(取代了原来的StackedInline),现在输入框显得更加紧凑了:

 

 

 

Customize the admin change list

定制列表界面

 

Now that the Poll admin page is looking good, let's make some tweaks to the "change list" page -- the one that displays all the polls in the system.

现在Poll的管理页面看起来不错了,下面我们来改善改善“change list”页面。

 

Here's what it looks like at this point:

下面是现在的列表页面:



 

 

By default, Django displays the str() of each object. But sometimes it'd be more helpful if we could display individual fields. To do that, use the list_display admin option, which is a tuple of field names to display, as columns, on the change list page for the object:

默认情况下,Django显示的是对所有对象进行str()处理后的结果。但是如果我们能够显示字段名称的话就更直观了。在管理模型中加入list_display字段,这字段是元组类型,字段的元素就是要在列表页面上要显示的数据库字段的名称。

class PollAdmin(admin.ModelAdmin):

    # ...

    list_display = ('question', 'pub_date')

 

Just for good measure, let's also include the was_published_today custom method from Tutorial 1:

另外,我们也要加上在第一部分中提到的was_published_today方法:

class PollAdmin(admin.ModelAdmin):

    # ...

    list_display = ('question', 'pub_date', 'was_published_today')

 

Now the poll change list page looks like this:

现在页面看起来就像这样:



 

 

You can click on the column headers to sort by those values -- except in the case of the was_published_today header, because sorting by the output of an arbitrary method is not supported. Also note that the column header for was_published_today is, by default, the name of the method (with underscores replaced with spaces). But you can change that by giving that method a short_description attribute:

你可以点击表头列来进行排序——除了was_published_today这一列,因为并不支持根据方法排序。还要注意到表头上默认情况下显示的就是方法名(下划线会被空格替换)。你可以添加方法的short_description属性来改变这个显示值:

def was_published_today(self):

    return self.pub_date.date() == datetime.date.today()

was_published_today.short_description = 'Published today?'

 

Let's add another improvement to the Poll change list page: Filters. Add the following line to PollAdmin:

现在加上给Poll的列表页面坐垫改进:筛选。在PollAdmin类中加入下面的代码:

list_filter = ['pub_date']

 

That adds a "Filter" sidebar that lets people filter the change list by the pub_date field:

右边多了个“Filter”边栏,现在用户可以根据pub_date字段对数据做筛选了。



 
 

The type of filter displayed depends on the type of field you're filtering on. Because pub_date is a DateTimeField, Django knows to give the default filter options for DateTimeFields: "Any date," "Today," "Past 7 days," "This month," "This year."

显示的筛选类型是根据筛选字段的类型决定的。pub_dateDateTimeField类型,Django知道对应的筛选选项:"Any date" "Today" "Past 7 days" "This month" "This year"

 

This is shaping up well. Let's add some search capability:

现在来加上搜索的功能:

search_fields = ['question']

 

That adds a search box at the top of the change list. When somebody enters search terms, Django will search the question field. You can use as many fields as you'd like -- although because it uses a LIKE query behind the scenes, keep it reasonable, to keep your database happy.

上面的代码会在列表页面的上方加上搜索框。输入搜索词时,Django会根据搜索词在question字段进行匹配。你喜欢用多少字段查询都可以——但是为了数据库性能,尽量合理地使用字段,因为在底层部分搜索使用的是LIKE查询。

 

Finally, because Poll objects have dates, it'd be convenient to be able to drill down by date. Add this line:

最后,因为Poll对象有日期字段,根据日期来对纪录进行分层是很便捷的。加上下面这一行:

date_hierarchy = 'pub_date'

 

That adds hierarchical navigation, by date, to the top of the change list page. At top level, it displays all available years. Then it drills down to months and, ultimately, days.

现在在列表页面的上方加上了基于日期的分级导航功能。在最高级,显示所有的年份,然后详细显示所有有记录的月份和天。

 

Now's also a good time to note that change lists give you free pagination. The default is to display 50 items per page. Change-list pagination, search boxes, filters, date-hierarchies and column-header-ordering all work together like you think they should.

在列表页面还有分页功能。默认每页显示50条纪录。列表页面的分页、搜索、筛选、日期分组和表头列排序功能都能和谐地一起工作。

 

Customize the admin look and feel

定制管理页面外观

 

Clearly, having "Django administration" at the top of each admin page is ridiculous. It's just placeholder text.

显而易见,在管理页面的上方显示“Django Administration”是有点雷人的。其实这里只是一段占位文字而已,可以进行替换。

 

That's easy to change, though, using Django's template system. The Django admin is powered by Django itself, and its interfaces use Django's own template system. (How meta!)

使用Django的模板系统可以很容易的修改。Django管理后台是由Django自身生成的,使用Django自身的模版系统就可以修改界面。

 

Open your settings file (mysite/settings.py, remember) and look at the TEMPLATE_DIRS setting. TEMPLATE_DIRS is a tuple of filesystem directories to check when loading Django templates. It's a search path.

打开配置文件(mysite/settings.py),看到TEMPLATE_DIRS设置。TEMPLATE_DIRS是由一串文件路径组成的元组,在读取Django模板时会依次检查这些路径。

 

By default, TEMPLATE_DIRS is empty. So, let's add a line to it, to tell Django where our templates live:

默认情况下TEMPLATE_DIRS是空的,所以我们加上一行代码告诉Django模板文件放在哪里:

TEMPLATE_DIRS = (

    "/home/my_username/mytemplates", # Change this to your own directory.

)

 

Now copy the template admin/base_site.html from within the default Django admin template directory (django/contrib/admin/templates) into an admin subdirectory of whichever directory you're using in TEMPLATE_DIRS. For example, if your TEMPLATE_DIRS includes "/home/my_username/mytemplates", as above, then copy django/contrib/admin/templates/admin/base_site.html to /home/my_username/mytemplates/admin/base_site.html. Don't forget that admin subdirectory.

Then, just edit the file and replace the generic Django text with your own site's name as you see fit.

现在从Django默认的管理后台模板路径(django/contrib/admin/templates)下拷贝admin/base_site.html文件到TEMPLATE_DIRS中任何一个目录的admin子目录下。比如你的TEMPLATE_DIRS包含“/home/my_username/mytemplates”,按照上面所说的,拷贝django/contrib/admin/templates/admin/base_site.html/home/my_username/mytemplates/admin/base_site.html,不要忘了admin子目录。然后编辑文件,根据你的需要把原来的文本替换成你自己站点的名字。

 

Note that any of Django's default admin templates can be overridden. To override a template, just do the same thing you did with base_site.html -- copy it from the default directory into your custom directory, and make changes.

注意Django默认的管理页面模板是可以重写的。只要像刚才处理base_site.html一样就可以进行重写——从默认的目录下拷贝到你自己的目录,然后修改即可。

 

Astute readers will ask: But if TEMPLATE_DIRS was empty by default, how was Django finding the default admin templates? The answer is that, by default, Django automatically looks for a templates/ subdirectory within each app package, for use as a fallback. See the template loader documentation for full information.

细心的读者会问:如果TEMPLATE_APPS默认情况下是空,那Django是怎么找到管理后台的默认模板的呢?其实在根据TEMPLATE_APPS设置找不到模板的情况下,Django会自动在每个程序的包下查找templates目录及其子目录。详细内容请查阅template loader文档。

 

Customize the admin index page

定制管理页面首页

 

On a similar note, you might want to customize the look and feel of the Django admin index page.

By default, it displays all the apps in INSTALLED_APPS that have been registered with the admin application, in alphabetical order. You may want to make significant changes to the layout. After all, the index is probably the most important page of the admin, and it should be easy to use.

你可能还想修改Django管理页面的首页的效果。一般情况下首页上会以字母顺序显示所有在INSTALL_APPS内所有注册了管理功能的程序。你可能想在页面布局上做大修改。总之,管理页面上最重要的页面就是首页,它应该对用户非常友好。

 

The template to customize is admin/index.html. (Do the same as with admin/base_site.html in the previous section -- copy it from the default directory to your custom template directory.) Edit the file, and you'll see it uses a template variable called app_list. That variable contains every installed Django app. Instead of using that, you can hard-code links to object-specific admin pages in whatever way you think is best.

你要修改的页面就是admin/index.html。(跟上一节处理admin/base_site.html一样,拷贝到自定义的模板)。编辑文件就能看到有个叫做app_list的模板变量。这个变量包含了所有工程中可用的Django程序。你可以把这一段重写,修改成适合你的系统的页面。

 

When you're comfortable with the admin site, read part 3 of this tutorial to start working on public poll views.

熟悉了Django管理后台之后,开始第三部分来学学视图的功能。

 

 

评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics