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將會在里面。
