admin組件使用html
admin源碼解析python
Django提供了基於web的管理工具git
Django 自動管理工具是 django.contrib 的一部分。你能夠在項目的 settings.py 中的web
django
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"app01"
]django.contrib是一套龐大的功能集,它是Django基本代碼的組成部分。設計模式
一般在生成項目的時候會在urls.py中自動設置好瀏覽器
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]當這一切配置好後,Django管理工具就能夠運行了。服務器
啓動開發服務器,而後在瀏覽器中訪問 http://127.0.0.1:8000/admin/,獲得登錄界面,session
你能夠經過命令 python manage.py createsuperuser 來建立超級用戶。app
爲了讓 admin 界面管理某個數據模型,咱們須要先註冊該數據模型到 admin
from django.db import models
# Create your models here.
class Author(models.Model):
name=models.CharField( max_length=32)
age=models.IntegerField()
def __str__(self):
return self.name
class Publish(models.Model):
name=models.CharField( max_length=32)
email=models.EmailField()
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField( max_length=32)
publishDate=models.DateField()
price=models.DecimalField(max_digits=5,decimal_places=2)
publisher=models.ForeignKey(to="Publish")
authors=models.ManyToManyField(to='Author')
def __str__(self):
return self.title
在admin中只須要將Model中的某個類註冊,便可在Admin中實現增刪改查的功能,如:
admin.site.register(models.UserInfo)
可是這種方式比較簡單,若是想進行更多的定製操做,須要利用ModelAdmin進行操做,
如:
方式一:
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd',)
admin.site.register(models.UserInfo, UserAdmin) # 第一個參數能夠是列表
方式二:
ModelAdmin中提供了大量的可定製功能,如:
list_display,列表時,定製顯示的列。
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd', 'xxxxx')
def xxxxx(self, obj):
return "xxxxx"
list_display_links,列表時,定製列能夠點擊跳轉。
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd', 'xxxxx')
list_display_links = ('pwd',)
list_filter,列表時,定製右側快速篩選。
list_select_related,列表時,連表查詢是否自動select_related
list_editable,列表時,能夠編輯的列
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd','ug',)
list_editable = ('ug',)
search_fields,列表時,模糊搜索的功能
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
search_fields = ('user', 'pwd')
date_hierarchy,列表時,對Date和DateTime類型進行搜索
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
date_hierarchy = 'ctime'8 inlines,詳細頁面,若是有其餘表和當前表作FK,那麼詳細頁面能夠進行動態增長和刪除
class UserInfoInline(admin.StackedInline): # TabularInline
extra = 0
model = models.UserInfo
class GroupAdminMode(admin.ModelAdmin):
list_display = ('id', 'title',)
inlines = [UserInfoInline, ]9 action,列表時,定製action中的操做
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
# 定製Action行爲具體方法
def func(self, request, queryset):
print(self, request, queryset)
print(request.POST.getlist('_selected_action'))
func.short_description = "中文顯示自定義Actions"
actions = [func, ]
# Action選項都是在頁面上方顯示
actions_on_top = True
# Action選項都是在頁面下方顯示
actions_on_bottom = False
# 是否顯示選擇個數
actions_selection_counter = True10 定製HTML模板
add_form_template = None
change_form_template = None
change_list_template = None
delete_confirmation_template = None
delete_selected_confirmation_template = None
object_history_template = None11 raw_id_fields,詳細頁面,針對FK和M2M字段變成以Input框形式
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
raw_id_fields = ('FK字段', 'M2M字段',)12 fields,詳細頁面時,顯示字段的字段
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
fields = ('user',)13 exclude,詳細頁面時,排除的字段
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
exclude = ('user',)14 readonly_fields,詳細頁面時,只讀字段
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
readonly_fields = ('user',)15 fieldsets,詳細頁面時,使用fieldsets標籤對數據進行分割顯示
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
fieldsets = (
('基本數據', {
'fields': ('user', 'pwd', 'ctime',)
}),
('其餘', {
'classes': ('collapse', 'wide', 'extrapretty'), # 'collapse','wide', 'extrapretty'
'fields': ('user', 'pwd'),
}),
)16 詳細頁面時,M2M顯示時,數據移動選擇(方向:上下和左右)
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
filter_vertical = ("m2m字段",) # 或filter_horizontal = ("m2m字段",)17 ordering,列表時,數據排序規則
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
ordering = ('-id',)
或
def get_ordering(self, request):
return ['-id', ]\18. radio_fields,詳細頁面時,使用radio顯示選項(FK默認使用select)
radio_fields = {"ug": admin.VERTICAL} # 或admin.HORIZONTAL
19 form = ModelForm,用於定製用戶請求時候表單驗證
from app01 import models
from django.forms import ModelForm
from django.forms import fields
class MyForm(ModelForm):
others = fields.CharField()
class Meta:
model = models = models.UserInfo
fields = "__all__"
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
form = MyForm20 empty_value_display = "列數據爲空時,顯示默認值"
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
empty_value_display = "列數據爲空時,默認顯示"
list_display = ('user','pwd','up')
def up(self,obj):
return obj.user
up.empty_value_display = "指定列數據爲空時,默認顯示"例子:
from django.contrib import admin
# Register your models here.
from .models import *
class BookInline(admin.StackedInline): # TabularInline
extra = 0
model = Book
class BookAdmin(admin.ModelAdmin):
list_display = ("title",'publishDate', 'price',"foo","publisher")
list_display_links = ('publishDate',"price")
list_filter = ('price',)
list_editable=("title","publisher")
search_fields = ('title',)
date_hierarchy = 'publishDate'
preserve_filters=False
def foo(self,obj):
return obj.title+str(obj.price)
# 定製Action行爲具體方法
def func(self, request, queryset):
print(self, request, queryset)
print(request.POST.getlist('_selected_action'))
func.short_description = "中文顯示自定義Actions"
actions = [func, ]
# Action選項都是在頁面上方顯示
actions_on_top = True
# Action選項都是在頁面下方顯示
actions_on_bottom = False
# 是否顯示選擇個數
actions_selection_counter = True
change_list_template="my_change_list_template.html"
class PublishAdmin(admin.ModelAdmin):
list_display = ('name', 'email',)
inlines = [BookInline, ]
admin.site.register(Book, BookAdmin) # 第一個參數能夠是列表
admin.site.register(Publish,PublishAdmin)
admin.site.register(Author)
單例模式(Singleton Pattern)是一種經常使用的軟件設計模式,該模式主要目的是確保
某一個類只有一個實例存在。當咱們但願在整個系統中,某個類只能出現一個實例
時,單例對象就能派上用場。
好比,某個服務器程序的配置信息存放在一個文件中,客戶端經過一個APPConfig
的類來讀取配置文件的信息。若是在程序運行期間,有不少地方須要使用配置文
件的內容,也就是說,不少地方都須要APPConfig的實例對象,而這樣會嚴重浪費
內存資源,尤爲是在配置文件內容不少的狀況下。事實上,相似AppConfig這樣的
類,咱們但願在程序運行期間只存在一個實例對象。
在python中,咱們能夠用不少種方式來實現單例模式:
使用模塊(模塊的導入)
使用__new__
使用裝飾器(decorator)
使用元類(metaclass)
(1)使用__new__
爲了使類只能出現一個實例,咱們可使用__new__來控制實例的建立過程,代碼
以下:
class Singleton(object):
_instance = None
def __new__(cls, *args, **kw):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)
return cls._instance
class MyClass(Singleton):
a = 1在上面的代碼中,咱們將類的實例和一個類變量instance關聯起來,若是cls.instance爲None則創
建實例,不然直接返回cls._instance
執行狀況:
>>> one = MyClass()
>>> two = MyClass()
>>> one == two
True
>>> one is two
True
>>> id(one), id(two)
(4303862608, 4303862608)(2)使用模塊
其實,Python 的模塊就是自然的單例模式,由於模塊在第一次導入時,會生成
.pyc
文件,當第二次導入時,就會直接加載
.pyc
文件,而不會再次執行模塊代碼。所以,咱們只需把相關的函數和數據定義在一個模塊中,就能夠得到一個單例對象了。若是咱們真的想要一個單例類,可
以考慮這樣作:
# mysingleton.py
class My_Singleton(object):
def foo(self):
pass
my_singleton = My_Singleton()將上面的代碼保存在文件
mysingleton.py
中,而後這樣使用:from mysingleton import my_singleton
my_singleton.foo()
<1>循環加載執行全部已經註冊的app中的admin.py文件
def autodiscover():
autodiscover_modules('admin', register_to=site)<2>執行代碼
#admin.py
class BookAdmin(admin.ModelAdmin):
list_display = ("title",'publishDate', 'price')
admin.site.register(Book, BookAdmin)
admin.site.register(Publish)<3>admin.site
class AdminSite(object):...
# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site.
site = AdminSite()這裏應用的是一個單例模式,對於AdminSite類的一個單例模式,執行的每個app中的每個admin.site
都是一個對象。
<4>執行register方法
admin.site.register(Book, BookAdmin)
admin.site.register(Publish)
class ModelAdmin(BaseModelAdmin):pass
def register(self, model_or_iterable, admin_class=None, **options):
if not admin_class:
admin_class = ModelAdmin
# Instantiate the admin class to save in the registry
self._registry[model] = admin_class(model, self)
# 思考:在每個app的admin .py中加上
print(admin.site._registry) # 執行結果?到這裏,註冊結束!
<5>admin的URL配置
urlpatterns = [
url(r'^admin/', admin.site.urls),
]class AdminSite(object):
def get_urls(self):
from django.conf.urls import url, include
urlpatterns = []
# Add in each model's views, and create a list of valid URLS for the
# app_index
valid_app_labels = []
for model, model_admin in self._registry.items():
urlpatterns += [
url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)),
]
if model._meta.app_label not in valid_app_labels:
valid_app_labels.append(model._meta.app_label)
return urlpatterns
<6>url方法的擴展應用
from django.shortcuts import HttpResponse
def test01(request):
return HttpResponse("test01")
def test02(request):
return HttpResponse("test02")
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^ward/', ([
url(r'^test01/', test01),
url(r'^test02/', test02),
],None,None)),
]擴展優化
from django.conf.urls import url,include
from django.contrib import admin
from django.shortcuts import HttpResponse
def change_list_view(request):
return HttpResponse("change_list_view")
def add_view(request):
return HttpResponse("add_view")
def delete_view(request):
return HttpResponse("delete_view")
def change_view(request):
return HttpResponse("change_view")
def get_urls():
temp=[
url(r"^$".format(app_name,model_name),change_list_view),
url(r"^add/$".format(app_name,model_name),add_view),
url(r"^\d+/del/$".format(app_name,model_name),delete_view),
url(r"^\d+/change/$".format(app_name,model_name),change_view),
]
return temp
url_list=[]
for model_class,obj in admin.site._registry.items():
model_name=model_class._meta.model_name
app_name=model_class._meta.app_label
# temp=url(r"{0}/{1}/".format(app_name,model_name),(get_urls(),None,None))
temp=url(r"{0}/{1}/".format(app_name,model_name),include(get_urls()))
url_list.append(temp)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^ward/', (url_list,None,None)),
]