Django - 內置admin

Django內置的Admin是對於model中對應的數據表進行增刪改查提供的組件,使用方式有:html

Django內置的Admin是對於model中對應的數據表進行增刪改查提供的組件,使用方式有:


複製代碼
    依賴APP:
        django.contrib.auth
        django.contrib.contenttypes
        django.contrib.messages
        django.contrib.sessions

    模板的context_processors:
        django.contrib.auth.context_processors.auth
        django.contrib.messages.context_processors.messages

    中間件:
        django.contrib.auth.middleware.AuthenticationMiddleware 
        django.contrib.messages.middleware.MessageMiddleware
複製代碼
一. 配置路由

urlpatterns = [
        url(r'^admin/', admin.site.urls),
    ]
當前配置的路由能夠建立一些路由映射關係:

/admin/
/admin/login/
/admin/logout/
/admin/password_change/
/admin/password_change/done/

/admin/app名稱/model名稱/
/admin/app名稱/model名稱/add/
/admin/app名稱/model名稱/ID值/history/
/admin/app名稱/model名稱/ID值/change/
/admin/app名稱/model名稱/ID值/delete/

二. 定製Admin
在admin.py中只須要講Mode中的某個類註冊,便可在Admin中實現增刪改查的功能,如:


admin.site.register(models.UserInfo)
可是,這種方式比較簡單,若是想要進行更多的定製操做,須要利用ModelAdmin進行操做,如:


方式一:
    class UserAdmin(admin.ModelAdmin):
        list_display = ('user', 'pwd',)
 
    admin.site.register(models.UserInfo, UserAdmin) # 第一個參數能夠是列表
     
 
方式二:
    @admin.register(models.UserInfo)                # 第一個參數能夠是列表
    class UserAdmin(admin.ModelAdmin):
        list_display = ('user', 'pwd',)
ModelAdmin中提供了大量的可定製功能,如

1. list_display,列表時,定製顯示的列。


@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    list_display = ('user', 'pwd', 'xxxxx')
 
    def xxxxx(self, obj):
        return "xxxxx"
2. list_display_links,列表時,定製列能夠點擊跳轉。


@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    list_display = ('user', 'pwd', 'xxxxx')
    list_display_links = ('pwd',)
3. list_filter,列表時,定製右側快速篩選。


from django.utils.translation import ugettext_lazy as _
 
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    list_display = ('user', 'pwd')
 
    class Ugg(admin.SimpleListFilter):
        title = _('decade born')
        parameter_name = 'xxxxxx'
 
        def lookups(self, request, model_admin):
            """
            顯示篩選選項
            :param request:
            :param model_admin:
            :return:
            """
            return models.UserGroup.objects.values_list('id', 'title')
 
        def queryset(self, request, queryset):
            """
            點擊查詢時,進行篩選
            :param request:
            :param queryset:
            :return:
            """
            v = self.value()
            return queryset.filter(ug=v)
 
    list_filter = ('user',Ugg,)
4. list_select_related,列表時,連表查詢是否自動select_related

5. 分頁相關


# 分頁,每頁顯示條數
    list_per_page = 100
 
# 分頁,顯示所有(真實數據<該值時,纔會有顯示所有)
    list_max_show_all = 200
 
# 分頁插件
    paginator = Paginator
6. list_editable,列表時,能夠編輯的列


@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    list_display = ('user', 'pwd','ug',)
    list_editable = ('ug',)
7. search_fields,列表時,模糊搜索的功能


@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
     
    search_fields = ('user', 'pwd')
8. date_hierarchy,列表時,對Date和DateTime類型進行搜索


@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
 
    date_hierarchy = 'ctime'
9. preserve_filters,詳細頁面,刪除、修改,更新後跳轉回列表後,是否保留原搜索條件

10. save_as = False,詳細頁面,按鈕爲「Sava as new」 或 「Sava and add another」

11. save_as_continue = True,點擊保存並繼續編輯


save_as_continue = True
 
# 若是 save_as=True,save_as_continue = True, 點擊Sava as new 按鈕後繼續編輯。
# 若是 save_as=True,save_as_continue = False,點擊Sava as new 按鈕後返回列表。
 
New in Django 1.10.
12. save_on_top = False,詳細頁面,在頁面上方是否也顯示保存刪除等按鈕

13. inlines,詳細頁面,若是有其餘表和當前表作FK,那麼詳細頁面能夠進行動態增長和刪除


class UserInfoInline(admin.StackedInline): # TabularInline
    extra = 0
    model = models.UserInfo
 
 
class GroupAdminMode(admin.ModelAdmin):
    list_display = ('id', 'title',)
    inlines = [UserInfoInline, ]
14. 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 = True
15. 定製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 = None
16. raw_id_fields,詳細頁面,針對FK和M2M字段變成以Input框形式


@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
 
    raw_id_fields = ('FK字段', 'M2M字段',)
17. fields,詳細頁面時,顯示字段的字段


@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    fields = ('user',)
18. exclude,詳細頁面時,排除的字段


@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    exclude = ('user',)
19. readonly_fields,詳細頁面時,只讀字段


@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    readonly_fields = ('user',)
20. 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'),
        }),
    )
21. 詳細頁面時,M2M顯示時,數據移動選擇(方向:上下和左右)


@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    filter_vertical = ("m2m字段",) # 或filter_horizontal = ("m2m字段",)
22. ordering,列表時,數據排序規則


@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    ordering = ('-id',)
    或
    def get_ordering(self, request):
        return ['-id', ]
23. view_on_site,編輯時,是否在頁面上顯示view on set


view_on_site = False
或
def view_on_site(self, obj):
    return 'https://www.baidu.com'
24. radio_fields,詳細頁面時,使用radio顯示選項(FK默認使用select)


radio_fields = {"ug": admin.VERTICAL} # 或admin.HORIZONTAL
25. show_full_result_count = True,列表時,模糊搜索後面顯示的數據個數樣式


@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    # show_full_result_count = True # 1 result (12 total)
    # show_full_result_count = False  # 1 result (Show all)
    search_fields = ('user',)
26. formfield_overrides = {},詳細頁面時,指定現實插件


from django.forms import widgets
from django.utils.html import format_html
 
class MyTextarea(widgets.Widget):
    def __init__(self, attrs=None):
        # Use slightly better defaults than HTML's 20x2 box
        default_attrs = {'cols': '40', 'rows': '10'}
        if attrs:
            default_attrs.update(attrs)
        super(MyTextarea, self).__init__(default_attrs)
 
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, name=name)
        return format_html('<textarea {}>\r\n{}</textarea>',final_attrs, value)
 
 
 
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
 
    formfield_overrides = {
        models.models.CharField: {'widget': MyTextarea},
    }
27. prepopulated_fields = {},添加頁面,當在某字段填入值後,自動會將值填充到指定字段。


@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
 
    prepopulated_fields = {"email": ("user","pwd",)}
PS: DjangoAdmin中使用js實現功能,頁面email字段的值會在輸入:user、pwd時自動填充

28. 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 = MyForm
29. 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 = "指定列數據爲空時,默認顯示"
Admin 內部依賴

 

一. 配置路由

urlpatterns = [
        url(r'^admin/', admin.site.urls),
    ]

 

當前配置的路由能夠建立一些路由映射關係:django

/admin/
/admin/login/
/admin/logout/
/admin/password_change/
/admin/password_change/done/session

/admin/app名稱/model名稱/
/admin/app名稱/model名稱/add/
/admin/app名稱/model名稱/ID值/history/
/admin/app名稱/model名稱/ID值/change/
/admin/app名稱/model名稱/ID值/delete/app

二. 定製Admin

在admin.py中只須要講Mode中的某個類註冊,便可在Admin中實現增刪改查的功能,如:ide

admin.site.register(models.UserInfo)

 

可是,這種方式比較簡單,若是想要進行更多的定製操做,須要利用ModelAdmin進行操做,如:ui

方式一:
    class UserAdmin(admin.ModelAdmin):
        list_display = ('user', 'pwd',)
 
    admin.site.register(models.UserInfo, UserAdmin) # 第一個參數能夠是列表
     
 
方式二:
    @admin.register(models.UserInfo)                # 第一個參數能夠是列表
    class UserAdmin(admin.ModelAdmin):
        list_display = ('user', 'pwd',)

 

ModelAdmin中提供了大量的可定製功能,如url

1. list_display,列表時,定製顯示的列。spa

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    list_display = ('user', 'pwd', 'xxxxx')
 
    def xxxxx(self, obj):
        return "xxxxx"

 

2. list_display_links,列表時,定製列能夠點擊跳轉。插件

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    list_display = ('user', 'pwd', 'xxxxx')
    list_display_links = ('pwd',)

 

3. list_filter,列表時,定製右側快速篩選。code

from django.utils.translation import ugettext_lazy as _
 
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    list_display = ('user', 'pwd')
 
    class Ugg(admin.SimpleListFilter):
        title = _('decade born')
        parameter_name = 'xxxxxx'
 
        def lookups(self, request, model_admin):
            """
            顯示篩選選項
            :param request:
            :param model_admin:
            :return:
            """
            return models.UserGroup.objects.values_list('id', 'title')
 
        def queryset(self, request, queryset):
            """
            點擊查詢時,進行篩選
            :param request:
            :param queryset:
            :return:
            """
            v = self.value()
            return queryset.filter(ug=v)
 
    list_filter = ('user',Ugg,)

 

4. list_select_related,列表時,連表查詢是否自動select_related

5. 分頁相關

# 分頁,每頁顯示條數
    list_per_page = 100
 
# 分頁,顯示所有(真實數據<該值時,纔會有顯示所有)
    list_max_show_all = 200
 
# 分頁插件
    paginator = Paginator

 

6. list_editable,列表時,能夠編輯的列

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    list_display = ('user', 'pwd','ug',)
    list_editable = ('ug',)

 

7. search_fields,列表時,模糊搜索的功能

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
     
    search_fields = ('user', 'pwd')

 

8. date_hierarchy,列表時,對Date和DateTime類型進行搜索

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
 
    date_hierarchy = 'ctime'

 

9. preserve_filters,詳細頁面,刪除、修改,更新後跳轉回列表後,是否保留原搜索條件

10. save_as = False,詳細頁面,按鈕爲「Sava as new」 或 「Sava and add another」

11. save_as_continue = True,點擊保存並繼續編輯

save_as_continue = True
 
# 若是 save_as=True,save_as_continue = True, 點擊Sava as new 按鈕後繼續編輯。
# 若是 save_as=True,save_as_continue = False,點擊Sava as new 按鈕後返回列表。
 
New in Django 1.10.

 

12. save_on_top = False,詳細頁面,在頁面上方是否也顯示保存刪除等按鈕

13. inlines,詳細頁面,若是有其餘表和當前表作FK,那麼詳細頁面能夠進行動態增長和刪除

class UserInfoInline(admin.StackedInline): # TabularInline
    extra = 0
    model = models.UserInfo
 
 
class GroupAdminMode(admin.ModelAdmin):
    list_display = ('id', 'title',)
    inlines = [UserInfoInline, ]

 

14. 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 = True

 

15. 定製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 = None

 

16. raw_id_fields,詳細頁面,針對FK和M2M字段變成以Input框形式

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
 
    raw_id_fields = ('FK字段', 'M2M字段',)

 

17. fields,詳細頁面時,顯示字段的字段

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    fields = ('user',)

 

18. exclude,詳細頁面時,排除的字段

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    exclude = ('user',)

 

19. readonly_fields,詳細頁面時,只讀字段

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    readonly_fields = ('user',)

 

20. 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'),
        }),
    )

 

21. 詳細頁面時,M2M顯示時,數據移動選擇(方向:上下和左右)

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    filter_vertical = ("m2m字段",) # 或filter_horizontal = ("m2m字段",)

 

22. ordering,列表時,數據排序規則

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    ordering = ('-id',)
    或
    def get_ordering(self, request):
        return ['-id', ]

 

23. view_on_site,編輯時,是否在頁面上顯示view on set

view_on_site = False
或
def view_on_site(self, obj):
    return 'https://www.baidu.com'

 

24. radio_fields,詳細頁面時,使用radio顯示選項(FK默認使用select)

radio_fields = {"ug": admin.VERTICAL} # 或admin.HORIZONTAL

 

25. show_full_result_count = True,列表時,模糊搜索後面顯示的數據個數樣式

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    # show_full_result_count = True # 1 result (12 total)
    # show_full_result_count = False  # 1 result (Show all)
    search_fields = ('user',)

 

26. formfield_overrides = {},詳細頁面時,指定現實插件

from django.forms import widgets
from django.utils.html import format_html
 
class MyTextarea(widgets.Widget):
    def __init__(self, attrs=None):
        # Use slightly better defaults than HTML's 20x2 box
        default_attrs = {'cols': '40', 'rows': '10'}
        if attrs:
            default_attrs.update(attrs)
        super(MyTextarea, self).__init__(default_attrs)
 
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, name=name)
        return format_html('<textarea {}>\r\n{}</textarea>',final_attrs, value)
 
 
 
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
 
    formfield_overrides = {
        models.models.CharField: {'widget': MyTextarea},
    }

 

27. prepopulated_fields = {},添加頁面,當在某字段填入值後,自動會將值填充到指定字段。

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
 
    prepopulated_fields = {"email": ("user","pwd",)}

 

PS: DjangoAdmin中使用js實現功能,頁面email字段的值會在輸入:user、pwd時自動填充

28. 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 = MyForm

 

29. 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 = "指定列數據爲空時,默認顯示"
相關文章
相關標籤/搜索