Home  >  Article  >  Backend Development  >  Django management interface

Django management interface

黄舟
黄舟Original
2017-01-17 13:58:521368browse

As we’ve mentioned many times before, Django’s admin interface is one of the framework’s killer features, and most Django developers know that it’s time-saving and easy to use. Due to the popularity of this admin interface, it is common for
Django developers to want to customize and extend it.


The last few sections of Django admin site introduce some simple ways to customize parts of the admin interface. Before entering this chapter, please review that part of the material; it covers how to customize the change list and
edit forms of the management interface, and how to style the management interface consistent with the site.


The Django admin site also discusses when and how to use the admin interface, and since that material is a good starting point for the rest of this chapter, we’ll go over it here:


Obviously, data editing For work purposes, this admin interface is extremely useful (imagine that). If it is used to complete some kind of data entry work, this management interface is really unmatched. We suspect that most readers of this book have a ton of data entry tasks at their disposal.


The Django management interface pays special attention to users without technical background to use data entry; this is also the purpose of developing this feature. In the newspaper where Django was first developed, a typical online municipal water supply quality reporting system was developed with the following requirements:


§ The reporter responsible for the subject met with a developer to submit the existing data.


§ The developer designs a model around that data and develops a management interface for the reporter.


§ While the reporter enters the data into Django, the programmer can focus on developing the public access interface (the fun part!).


In other words, the primary purpose of the Django management interface is to facilitate content editors and programmers to work at the same time.


Of course, besides the obvious data entry tasks, we have found the admin interface to be useful in a number of other situations.


§ Check the data model: After defining a new data model, the first thing we have to do is run it in the management interface and enter some hypothetical data. Usually after an error in data modeling is discovered, the graphical model interface can be used to quickly find the crux.


§ Manage acquired data: Very little real data input is associated with a site like http://chicagocrime.org, as most data comes from automatically generated sources. However, when the data obtained is wrong and causes trouble, being able to easily find and modify the wrong data will help solve the problem.


With no or only slight customization, the Django management interface can handle most common situations. However, the very compromise in design that allows Django's admin interface to handle this common situation well means that it cannot handle some other editing models as well.


Later, we’ll discuss situations that the Django admin interface is not designed to handle, but first let’s step aside for a moment and discuss its design philosophy.


How to manage


At its core, the Django admin interface is designed for only one behavior:


Trusted users editing structured content.


Yes, it’s very simple, but that simplicity is based on a whole bunch of assumptions. The entire design philosophy of Django's admin interface follows directly from these assumptions, so let's dig into the meaning of the terms that appear in these subsequent sections.


Trusted Users


The admin interface is designed to be used by people you, the developer, trust. This doesn’t just mean authenticated people; it means that Django assumes that content editors can be trusted to do only the right thing.


In turn, this means that if you trust users, they can edit content without asking permission, and no one needs to give permission for their editing actions. Another implication is that, although the authentication system is powerful, as of this writing, it does not support access restrictions on an object-level basis. If you allow someone to edit their own news stories, you must be confident that the user will not edit other people's stories without permission.


Editing


The primary purpose of the Django admin interface is to allow users to edit data. This is obvious at first glance, but becomes a bit elusive and unusual on closer inspection.


For example, although the admin interface is very convenient for inspecting data (as just discussed), this is not its original design intention. As we talked about in Django Sessions, Users, and Registrations, it lacks view permissions. Django assumes that if someone in the admin interface can view something, they can also edit it.


There is one more important thing to note, and that is the lack of remote call workflow. If a particular task consists of a sequence of steps, there is no mechanism to ensure that those steps are completed in a particular order. The Django admin interface focuses on editing and does not care about the activities surrounding modifications. This avoidance of workflow also stems from the principle of trust: the management interface is designed with the idea that workflow is a human thing and does not need to be implemented in code.


Finally, something to note is the lack of aggregation in the admin interface. That is, displaying things like totals and averages is not supported. Again, the admin interface is for editing only - it expects you to do everything else by defining views.


Structured content


With the cooperation of other parts of Django, the management interface expects you to use structured data. Therefore, it only supports editing of data stored in Django models; for other data, such as data in the file system, you must customize the view to edit.


Let’s stop here


What is certain now is that Django’s management interface is not intended to be a universal tool for everyone; instead we choose to focus on one thing and complete it to perfection.


When expanding Django’s management interface, you must adhere to the same design concept. (Note that scalability is not our goal). Because everything can be done by customizing Django views, and because they can be easily integrated visually into the admin interface (described in the next chapter), the built-in opportunities for customizing the admin interface are intentionally a little limited.


It is important to remember that despite the complexity of the management interface, it is always just an application. Given enough time, any Django developer can do everything the admin interface can do. Therefore, we need to hope that a completely different admin interface will appear in the future. This new interface has a different set of assumptions and works in a completely different way.


Finally, at the time of writing, Django developers are working on a new management interface that will provide more customization flexibility. By the time you read this, these new features may have made their way into real Django releases. You can check with someone in the
Django community to see if the newforms-admin backbone code has been integrated.


Customized admin templates


Django provides some tools for customizing the built-in admin admin templates, which we will briefly introduce. For other tasks (such as workflow control, or more fine-grained permission management), you need to read the Creating a Custom Admin View section in this chapter.


Now, let’s take a look at how to quickly customize the appearance of the admin management interface. The Django admin site covers some of the most common tasks: changing the logo (for those spiky-haired bosses who hate the color blue), or providing a custom form.


Further goals often include changing some special items in the template. Each admin view, including the modification list, edit form, delete confirmation page, and history view, has an associated template that can be overridden in a variety of ways.


First, you can override the template globally. The admin view uses the standard template loading mechanism to find templates. So if you create a new template in the templates directory, Django will automatically load it. Global templates are listed in Table 17-1.局 Table 17-1. Global management template


View base template name

Change List admin/Change_list.html

Add/Edit Form Admin/Change_Form.html

Delete CONFIRMIN/Delete_Confirmation.html

Object history admin/object_history.html



Most of the time, you may just want to modify an individual object or application, rather than modify global settings. Therefore, every admin view always first looks for templates related to the model or application. The order in which these views look for templates is as follows:

§ admin/<app_label>/<object_name>/<template>.html
§ admin/<app_label>/<template>.html
§ admin/<template>.html

For example, in the books application, the view of the Book module's add/edit form will look for templates in the following order:

§ admin/books/book/change_form.html
§ admin/books/change_form.html
§ admin/change_form.html

Custom model template


Most of the time, you want to use the first template to create a template for a specific model. Usually, the best approach is to extend the base template and add information to the blocks defined in the base template.


For example, we want to add some help text at the top of that book page. Probably something like the form shown in Figure 17-1.


Figure 17-1. A custom management editing form.


这做起来非常容易:只要建立一个admin/bookstore/book/change_form.html模板,并输入下面的代码:

{% extends "admin/change_form.html" %}
{% block form_top %}
<p>Insert meaningful help message here...</p>
{% endblock %}

所有这些模板都定义了一些可以被覆盖的块。对于大多数的应用程序来说,代码就是最好的文档,所以我们鼓励你能够详细阅读admin的模板来获得最新的信息(它们在django/contrib/admin/templates/)。


自定义JavaScript


这些自定义模型模板的常见用途包括,给admin页面增加自定义的javascript代码来实现一些特殊的视图物件或者是客户端行为。


幸运的是,这可以更简单。每一个admin模板都定义了{% block extrahead %},你可以在93f0f5c25f18dab9d176bd4f6de5d30e元素中加入新的内容。例如你想要增加jQuery(http://jquery.com/)到你的admin历史中,可以这样做:

{% extends "admin/object_history.html" %}
{% block extrahead %}
<script src="http://media.example.com/javascript/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
// code to actually use jQuery here...
</script>
{% endblock %}

备注


我们并不知道你为什么需要把jQuery放入到历史页中,但是这个例子可以被用到任何的模板中。


你可以使用这种技巧,加入任何的javascript代码。


创建自定义管理视图


现在,想要往Django的admin管理接口添加自定义行为的人,可能开始觉得有点奇怪了。我们这里所讲的都是如何改变admin管理接口的外观。他们都在喊:如何才能改变admin管理接口的内部工作机制。


首先要提的一点是,这并不神奇。admin管理接口并没有做任何特殊的事情,它只不过是和其他一些视图一样,简单地处理数据而已。


确实,这里有相当多的代码;它必须处理各种各样的操作,字段类型和设置来展示模型的行为.当你注意到ADMIN界面只是一系列视图(Views)的集合,增加自定义的管理视图就变得容易理解了。


作为举例,让我们为Django管理站点中的图书申请增加一个出版商报告的视图。建立一个admin视图用于显示被出版商分好类的书的列表,一个你要建立的自定义admin报告试图的极典型的例子。


首先,在我们的URLconf中连接一个视图。插入下面这行:

(r&#39;^admin/books/report/$&#39;, &#39;mysite.books.admin_views.report&#39;),
在将这行加入这个admin视图之前,原本的URLconf应该是这样:
from django.conf.urls.defaults import *
urlpatterns = patterns(&#39;&#39;,
(r&#39;^admin/bookstore/report/$&#39;, &#39;bookstore.admin_views.report&#39;),
(r&#39;^admin/&#39;, include(&#39;django.contrib.admin.urls&#39;)),
)

为什么要将定制试图置于管理内容之前呢?回想一下,Django是按照顺序处理 URL
匹配式的。管理内容几乎匹配内容点之后所有的东西,因此如果我们把这几行的顺序颠倒一下, Django将会为该匹配式找到一个车内建管理视图,并将试图在books应用程序中为Report模型再入更新列表,而这却是不存在的。


现在我们开始写视图。为了简单起见,我们只把所有书籍加载到上下文中,让模板用{% regroup %}标签来处理分组操作。创建books/admin_views.py文件并写入以下内容:

from mysite.books.models import Book
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.admin.views.decorators import staff_member_required
def report(request):
return render_to_response(
"admin/books/report.html",
{&#39;book_list&#39; : Book.objects.all()},
RequestContext(request, {}),
)
report = staff_member_required(report)

因为我们但分组操作留给了模板,该视图非常简单。然而,有几段微妙的细节值得我们搞清楚。


我们使用了django.contrib.admin.views.decorators中的staff_member_required修饰器。该修饰器与Django会话、用户和注册中讨论的login_required类似,但它还检查所指定的用户是否标记为内部人员,以决定是否允许他访问管理界面。


该修饰器保护所有内容的管理视图,并使得视图的身份验证逻辑匹配管理界面的其它部分。


我们在admin/之下解析了一个模板。尽管并非严格要求如此操作,将所有管理模板分组放在admin目录中是个好的做法。我们也将应用程序所有的模板放置在名叫books的目录中,这也是最佳实践。


我们将RequestContext用作render_to_response的第三个参数(``context_instance``)。这就确保了模板可访问当前用户的信息。


参看Django输出非HTML内容了解更多关于RequestContext的信息。


最后, 
我们为这个视图做一个模板。我们将扩展内置管理模板,以使该视图明确地成为管理界面的一部分.

{% extends "admin/base_site.html" %}
{% block title %}List of books by publisher{% endblock %}
{% block content %}
<div id="content-main">
<h1>List of books by publisher:</h1>
{% regroup book_list|dictsort:"publisher.name" by publisher as books_by_publisher %}
{% for publisher in books_by_publisher %}
<h3>{{ publisher.grouper }}</h3>
<ul>
{% for book in publisher.list|dictsort:"title" %}
<li>{{ book }}</li>
{% endfor %}
</ul>
{% endfor %}
</div>
{% endblock %}

通过扩展admin/base_site.html,我们没费丝毫气力就得到了 Django管理界面的外观。图
17-2 我展示了像这样的一个最终结果。


图 17-2.一个自定义按出版商归类的图书管理视图


使用该技术,你可以向管理界面中添加任何你梦想中的东西。需要记住的是这些被叫做定制管理视图实际不过是普通的 Django视图,你可以使用在本书其它部分所学到的技术制作出符合自己需要的复杂管理界面。


下面用自定义admin视图的一些概念总结一下本章。


覆盖内置视图


有时缺省的管理视图无法完成某项工作。你可以轻松地换上自己的定制视图;只需要用自己的 URL遮蔽内建的管理视图。也就是说,如果在 URLConf中你的视图出现在缺省管理视图之前,你的视图将取代缺省视图被调用。


举例来说,我们可以用一个让用户简单输入 ISBN的窗体来取代内建的书籍创建视图。然后,我们可以从http://isbn.nu/查询该书的信息,并自动地创建对象。


这样的视图的代码留给读者作为一个练习,重要的部分是这个 URLconf代码片断:

(r&#39;^admin/bookstore/book/add/$&#39;, &#39;mysite.books.admin_views.add_by_isbn&#39;),

如果这个代码片段在 URLConf中出现于管理 URL
之前,add_by_isbn视图将完全取代标准的管理视图。


按照这种方式,我们可以替换删除确认页、编辑页面或者管理界面的其它任何部分

以上就是Django 管理界面的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn