Django 14天從小白到進階- Day2 玩轉admin組件


本節內容

 

  • 路由系統
  • models模型
  • admin 
  • views視圖
  • template模板

 

Django Admin介紹

admin 是django 自帶的用來讓你進行數據庫管理的web app.
提供了很多定制化功能,你甚至可以用它來進行公司內部的內容管理

 

啟用admin

你用startproject命令創建項目時django admin就默認啟用了

For reference, here are the requirements:

  1. Add 'django.contrib.admin' to your INSTALLED_APPS setting.
  2. The admin has four dependencies - django.contrib.auth, django.contrib.contenttypes, django.contrib.messages and django.contrib.sessions. If these applications are not in your INSTALLED_APPS list, add them.
  3. Add django.contrib.auth.context_processors.auth and django.contrib.messages.context_processors.messages to the 'context_processors' option of the DjangoTemplates backend defined in your TEMPLATES as well as django.contrib.auth.middleware.AuthenticationMiddleware and django.contrib.messages.middleware.MessageMiddleware to MIDDLEWARE. These are all active by default, so you only need to do this if you’ve manually tweaked the settings.
  4. Determine which of your application’s models should be editable in the admin interface.

admin 訪問地址

http://localhost:yourport/admin/, by default.

為什么會讓登錄?哪來的用戶信息?django自帶了一套用戶認證系統,admin就用了這個, 所以你想登錄,先創建管理員賬號。

python manage.py createsuperuser

 

然后你就開心的登錄進去了呀

發現只有這么個東西, 什么東東?

這就是django自帶的用戶認證系統的2張表,用於管理賬戶和賬戶組信息。

那接下來要干什么呢? 注意django admin的作用是讓你管理各app下的數據庫表,實現可以通過Web頁面就完成對數據的增刪改查噢。 admin不會沒事閑的自己把你創建的表拿過來管理,你得把你寫的表在admin里注冊一下才行。 

在每個app下有個admin.py文件 ,在那里面注冊你想要被管理的表

from django.contrib import admin

# Register your models here.

from app01 import models


admin.site.register(models.Article)
admin.site.register(models.Account)

 

然后刷新下頁面,新添加的2個表就出來了  

admin定制

你可以定義每張表顯示哪些字段、對某些字段進行過濾、允許搜索等功能,這就需要定制一下admin的類了

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title','pub_date','account','read_count')
    
admin.site.register(Article, ArticleAdmin)

一下子就好看了,真是神奇呀。

就喜歡你這沒見識的樣子,別急,還有很多nb的功能呢,一起來看下。

看來這個list_display就是定義表數據要展示哪些字段的,除了這個屬性,admin 還提供了哪些其它功能呢?

 

fields 決定對表進行修改時展示哪些字段

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title','pub_date','account','read_count')
    fields = ['title','account','pub_date']

 

還可以多個字段顯示在一行。

    fields = ['title','account',('pub_date','read_count')]

 

exclude 不展示哪些字段  

date_hierarchy = 'pub_date'  按日期分類顯示數據  

You can also specify a field on a related model using the __ lookup, for example:
date_hierarchy = 'author__pub_date'

fieldsets 分組顯示

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title','pub_date','account','read_count')
    date_hierarchy = 'pub_date'

    fieldsets = (('文章相關',{
        'fields':('title','content'),
        'classes': ('wide', 'extrapretty'),
    }),('高級',{
        'classes':('collapse',),
        'fields':(('account','read_count'),'pub_date')
    }))

上面的classes 是用於設定字段樣式,2個默認自帶的樣式是collapse 和wide

filter_horizontal,filter_vertical 均用於多對多字段 

filter_horizontal = ['tags',]

 

list_display  定義表數據顯示哪些列

除了表中有的字段,models自己定義的字段也能放入list_display

from django.db import models
from django.contrib import admin

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()

    def decade_born_in(self):
        return self.birthday.strftime('%Y')[:3] + "0's"
    decade_born_in.short_description = 'Birth decade'

class PersonAdmin(admin.ModelAdmin):
    list_display = ('name', 'decade_born_in')

甚至還能玩出花樣  

from django.utils.html import format_html

class Tag(models.Model): """文章標簽表""" name = models.CharField(max_length=64,unique=True) date = models.DateTimeField(auto_now_add=True) color_code = models.CharField(max_length=6) def colored_name(self): return format_html( '<span style="color: #{};">{}</span>', self.color_code, self.name, ) def __str__(self): return self.name
class TagAdmin(admin.ModelAdmin):
    list_display = ['name','colored_name']

竟然出現了樣式,神奇。

  

list_display_links = ('first_name', 'last_name') 點下這2個字段就跳到修改頁

list_filter 過濾,把要過濾的字段放到對應列表里就可以

list_filter = ('register_date',)

  

list_per_page = 20 每頁顯示20條數據

  

radio_fields 把外鍵或choice字段由下拉框變成單選框

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title','pub_date','account','read_count')
    date_hierarchy = 'pub_date'
    filter_horizontal = ['tags',]
    radio_fields = {'account': admin.VERTICAL}

 

 

自動補全

autocomplete_fields = ['account',] 自動補全,外鍵查詢數據多時,方便查找  

 

raw_id_fields  言語無法表示的字段

就把外鍵變成這樣子

 

readonly_fields = ('address_report',)  只讀字段

search_fields  模糊查找

search_fields = ['account__username','title']

 

  

好啦,就先講這些吧, 當然admin還有很多更高級的功能,不過先會這些就夠了,以后會深入再講的。  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM