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将会在里面。

相关文章
相关标签/搜索