1. django站点管理的特性: 它读取你模型中的元数据,然后提供给你一个强大而且可以使用的界面,网站管理者可以用它立即工作。
2. django的管理工具被称作 django.contrib.admin
3. django.contrib中其他的可用特性: 用户鉴别系统(django.contrib.auth)、支持匿名会话(django.contrib.sessioins)以及用户评注系统(django.contrib.comments)
对应的英文网站: https://djangobook.com/django-admin-site/
激活django的管理界面
- 确保 INSTALLED_APPS 中有 'django.contrib.auth','django.contrib.contenttypes'和'django.contrib.sessions'
- 确保 MIDDLEWARE_CLASSES 中有 'django.middleware.common.CommonMiddleware'、'django.contrib.sessions.middleware.SessionMiddleware'和'django.contrib.auth.middleware.AuthenticationMiddleware'
- 运行 python manage.py syncdb ,会出现如下:
总结: 用 django-admin startproject myapp 创建一个新项目,生成的代码,不要乱注释,尤其是INSTALLED_APPS和MIDDLEWARE_CLASSES中的,还有确保url中有 (r'^admin/', include(admin.site.urls)) 这条路径,
然后执行 python manage.py syncdb ,执行之后按提示操作,最后访问页面 http://127.0.0.1:8000/admin/ (此处需更实际IP和端口变化网址)用创建好的用户名和密码登录即可,登录后的界面是:
有网友说:新版本的Django已经不是python manage.py syncdb了改为: 先执行python manage.py makemigrations再执行python manage.py migrate最后执行python manage.py createusperuser
使用管理工具
Each type of data in the Django admin site has a change list and an edit form. Change lists show you all the available objects in the database, and edit forms let you add, change or delete particular records in your database. Click the “Change” link in the “Users” row to load the change list page for users (Figure 5-3).
在django站点中的各种类型的数据都有change list和 edit list. change lists 展示了数据库中所有你可以获得的数据。edit lists可以让你增加、修改、删除数据中的数据。在user那一行,点击 change 按钮,出现的页面如图:
Figure 5-3: 用户列表页面
This page displays all users in the database; you can think of it as a prettied-up web version of a SELECT * FROM auth_user;
SQL query. If you’re following along with our ongoing example, you’ll only see one user here, but once you have more users, you’ll probably find the filtering, sorting and searching options useful.
这个页面展示了数据库中的所有用户,你可以当做是执行 SELECT * FROM auth_user; 的结果。如果你是一直跟着我们的教程走到这儿的,你将会在这里看到一个用户,但是,一旦你有很多用户,在这个页面你可以看见 过滤器、排序、搜索等有用的选项。
Filtering options are at right, sorting is available by clicking a column header, and the search box at the top lets you search by username. Click the username of the user you created, and you’ll see the edit form for that user (Figure 5-4). This page lets you change the attributes of the user, like the first/last names and various permissions.
过滤的选项在右边,当点击每一列的header时,就可以排序, 搜索框在顶部,让你可以根据用户名称来搜索。点击你创建的用户的用户名称,你可以看见编辑这个用户的表单(图5-4)。这个页面可以让你改变这个用户的信息,比如:first/last names 或者权限
Figure 5-4: 用户编辑表单
Note that the user’s password in not shown. As a security measure, Django doesn’t store raw passwords, so there is no way to retrieve a password, you have to change it.
处于安全考虑,用户的密码是未显示的。django不存储原始密码,所以你没有任何方法能找回密码,只能修改它。
Another thing to note here is that fields of different types get different widgets – for example, date/time fields have calendar controls, Boolean fields have checkboxes, character fields have simple text input fields.
另外需要注意的是:不同类型的字段会得到不同的小组件。举个例子——date/time类型有日历控制。Boolean 类型有复选框, 字符串类型有输入框
You can delete a record by clicking the delete button at the bottom left of its edit form. That’ll take you to a confirmation page, which, in some cases, will display any dependent objects that will be deleted, too. (For example, if you delete a publisher, any book with that publisher will be deleted, too!)
在编辑表单的左下角有删除按钮,你可以点击它删除记录。一旦你点击了删除按钮,页面会上会显示一个确认页面,在有些例子中,这里还会展示待删除对象的依赖对象,从而一起删除。(举例:你删除一个publisher,那么任何与该publisher相关的book也会被删除)
You can add a record by clicking “Add” in the appropriate column of the admin home page. This will give you an empty version of the edit page, ready for you to fill out. You’ll also notice that the admin interface handles input validation for you. Try leaving a required field blank or putting an invalid date into a date field, and you’ll see those errors when you try to save, as shown in Figure 5-5.
在管理站点的首页,在适当的列上点击 Add 按钮,可以添加一条记录。 一旦你点击了 Add 按钮,你将会进入编辑页面。在编辑页面是有输入校验的。当你在必填的输入框中未输入任何内容或者在应输入日期的地方输入了不合法的日期,当你点击 save 按钮时,你可以看到错误提示。如图5-5所示
Figure 5-5: 编辑表单展示的错误信息
When you edit an existing object, you’ll notice a History link in the upper-right corner of the window. Every change made through the admin interface is logged, and you can examine this log by clicking the History link (see Figure 5-6).
当你编辑一个存在的对象,你会在窗口的右上角看见一个可以查看history的链接。通过这个管理界面做的任何更改都会被记录,你可以点击 History link 查看日志。如图5-6所示:
Figure 5-6: 一个对象的历史界面
管理站点是怎么工作的
Behind the scenes, how does the admin site work?
在幕后,管理站点是如何工作的
It’s pretty straightforward. When Django loads at server startup, it runs the admin.autodiscover()
function. In earlier versions of Django, you used to call this function from urls.py
, but now Django runs it automatically. This function iterates over your INSTALLED_APPS
setting and looks for a file called admin.py
in each installed app. If an admin.py
exists in a given app, it executes the code in that file.
这非常简单。当django服务启动时,它会运行 admin.autodiscover() 函数。在django的早期版本中,你需要在 urls.py 中调用这个函数,但是现在它是自动运行的。这个函数会迭代你在 INSTALLED_APPS
中的配置,并且在每一个app中找名为admin.py的文件。
如果在给定的app中,找到了admin.py文件,它会执行admin.py文件中的代码。
The admin site will only display an edit/change interface for models that have been explicitly registered with admin.site.register()
entered into the app’s admin.py
file. This is why your books model is not displaying yet – we have not registered the model with the admin. We will get to that next.
管理网站在界面上仅展示已经显示在app的admin.py文件中用 admin.site.register() 注册的模型的 change和edit。这就是为什么你的 books 模型到现在还没有展示的原因——我们没有在admin中注册books模型。接下来将教你怎么注册。
The app django.contrib.auth
includes its own admin.py
, which is why Users and Groups showed up automatically in the admin. Other django.contrib
apps, such as django.contrib.redirects
, also add themselves to the admin, as do many third-party Django applications you might download from the web.
叫做 django.contrib.auth 的这个app,它有自己的admin.py文件,这就是为什么Users和Groups在管理站点能自动展示的原因。其他的 django.contrib
apps,比如:django.contrib.redirects
也把他们自己加到了admin中,如同许多第三方django应用你可用从web页面上下载一样。
Beyond that, the Django admin site is just a Django application, with its own models, templates, views and URLpatterns. You add it to your application by hooking it into your URLconf, just as you hook in your own views. You can inspect its templates, views and URLpatterns by poking around in django/contrib/admin
in your copy of the Django codebase – but don’t be tempted to change anything directly in there, as there are plenty of hooks for you to customize the way the admin site works.
除此之外,Django管理站点只是一个Django应用程序,有它自己的 models 、templates 、views 和URLpatters. 你可以通过把它挂钩到你的URL配置中,从而加入到你的应用中,和挂钩你自己的视图一样。你可以复制django/contrib/admin中的代码来查看
它的templates, views and URLpatterns,但是不要直接在django/contrib/admin中修改,因为那有很多的钩子来定制管理网站的工作方式。
将模型加入到Django Admin中
There’s one crucial part we haven’t done yet. Let’s add our own models to the admin site, so we can add, change and delete objects in our custom database tables using this nice interface. We’ll continue the books
example from Chapter 4, where we defined three models: Publisher, Author and Book. Within the books
directory (mysite_project\mysite\books
), startapp
should have created a file called admin.py
, if not, simply create one yourself and type in the following lines of code:
这儿还有一个关键部分我们没有完成。让我们把我们自己的模型加入到管理站点中,使得我们可以在漂亮的界面上增加、改变、删除我们在数据库中自定义的表。我们将继续以第四章的books为例讲解,就是那个我们定义了三个模型(Publisher、Author、Book)的那一章。在books目录下,若没有admin.py文件,那么你需要自己新建一个admin.py文件,在admin.py文件中写入如下代码:
# -*- coding:utf-8 -*- from django.contrib import admin from .models import Publisher, Author, Book admin.site.register(Publisher) #将模型注册到admin中,使得管理站点上能显示这个模型 admin.site.register(Author) admin.site.register(Book)
This code tells the Django admin site to offer an interface for each of these models. Once you’ve done this, go to your admin home page in your web browser (http://127.0.0.1:8000/admin/
), and you should see a “Books” section with links for Authors, Books and Publishers. You might have to stop and start the development server for the changes to take effect.
上述那些代码告诉django 管理站点为 用admin.site.register 注册的模型提供操作界面。再次浏览 http://192.168.171.128:8888/admin/ 就可以看到新注册的模型了(可能需要重启服务器使得改动生效),如图:
You now have a fully functional admin interface for each of those three models. That was easy!
现在,你可以为那3个模型中的任何一个提供功能齐全的管理界面。那非常简单。
Take some time to add and change records, to populate your database with some data. If you followed Chapter 4’s examples of creating Publisher
objects (and you didn’t delete them), you’ll already see those records on the publisher change list page.
花一点时间去增加或改变记录,从而将一些数据填入数据库。如果你遵循了第4章创建Publisher对象的示例(并且您没有删除它们),你将会在改变publisher页面看到那些记录。如图:
注:若在界面上添加中文报错 'ascii' codec can't encode characters in position 8-50: ordinal not in range(128)
解决方案: 在admin.py中写入如下代码:
import sys
reload(sys)
sys.setdefaultencoding('utf8')
One feature worth mentioning here is the admin site’s handling of foreign keys and many-to-many relationships, both of which appear in the Book
model. As a reminder, here’s what the Book
model looks like:
这里值得一提的一个特性是管理站点处理外键和多对多关系,这两个关系都出现在Book模型中。提醒一下,以下是Book模型的样子:
class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __str__(self): return self.title
On the Django admin site’s “Add book” page (http://192.168.171.128:8888/admin/books/book/add/), the publisher (a ForeignKey
) is represented by a select box, and the authors field (a ManyToManyField
) is represented by a multiple-select box. Both fields sit next to a green plus sign icon that lets you add related records of that type.
在Django管理站点的“添加书籍”页面(http://127.0.0.1:8000/admin/books/book/add/)上,publisher(ForeignKey)由选择框表示,authors字段(a ManyToManyField)由多选框表示。两个字段的右边都有绿色加号图标,点击它可以让你增加那个类型的记录,如图所示:
For example, if you click the green plus sign next to the “Publisher” field, you’ll get a pop-up window that lets you add a publisher. After you successfully create the publisher in the pop-up, the “Add book” form will be updated with the newly created publisher. Slick.
举例:如果你点击Publisher字段右边对应的那个绿色加号,你将会看到一个弹出窗口让你增加publisher。如果你在弹出窗口成功增加了一个publisher,那么"Add Book"表单的Publisher的下拉框中会自动更新,新创建的publiser将会在里面。