django站點管理——(一)

 

1. django站點管理的特性:  它讀取你模型中的元數據,而後提供給你一個強大並且可使用的界面,網站管理者能夠用它當即工做。python

2. django的管理工具被稱做 django.contrib.adminweb

3. django.contrib中其餘的可用特性:  用戶鑑別系統(django.contrib.auth)、支持匿名會話(django.contrib.sessioins)以及用戶評註系統(django.contrib.comments)數據庫

 對應的英文網站: https://djangobook.com/django-admin-site/django

 

激活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和端口變化網址)用建立好的用戶名和密碼登陸便可,登陸後的界面是:session

 

   有網友說:新版本的Django已經不是python manage.py syncdb了改成: 先執行python manage.py makemigrations再執行python manage.py migrate最後執行python manage.py createusperuserapp

 

使用管理工具函數

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

相關文章
相關標籤/搜索