WEB前端

Django中的admin自定制相关

2018-08-27  本文已影响27人  SlashBoyMr_wang

Django admin是Django 提供的基于 web 的管理工具。Django 自动管理工具是 django.contrib 的一部分。你可以在项目的 settings.py 中的 INSTALLED_APPS 看到它。django.contrib是一套庞大的功能集,它是Django基本代码的组成部分。

Django内置的Admin是对于model中对应的数据表进行增删改查提供的组件。

admin的内部依赖:
    依赖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

一、定制admin

from django.contrib import admin
from app import models
admin.site.register(models.UserInfo)
方式一:
    class UserAdmin(admin.ModelAdmin):#必须继承admin.ModelAdmin
        pass 
    admin.site.register(models.UserInfo, UserAdmin)  # 第一个参数可以是列表
      
方式二:
    @admin.register(models.UserInfo) # 第一个参数可以是列表
    class UserAdmin(admin.ModelAdmin):
        list_display = ('user', 'pwd',)

二、 ModelAdmin中提供的可定制功能简单示例

class UserInfo(admin.ModelAdmin):
   list_display = ("username","phone","email")

admin.site.register(models.UserInfo,UserInfo)
class UserInfo(admin.ModelAdmin):
    list_display = ("username","phone","email")
    list_display_links = ['username','phone','email']
admin.site.register(models.UserInfo,UserInfo)
class UserInfo(admin.ModelAdmin):
    list_display = ("username","phone","email")
    list_display_links = ['username','phone','email']
    list_filter = ['username','phone']#一般列表里面存放的字段都是一对多的字段,要不然就没什么意义了

admin.site.register(models.UserInfo,UserInfo)
class UserInfo(admin.ModelAdmin):
    list_display = ("username","phone","email")
    list_display_links = ['username','phone','email']
    list_filter = ['username','phone']#一般列表里面存放的字段都是一对多的字段,要不然就没什么意义了
    search_fields = ["username",'phone']

admin.site.register(models.UserInfo,UserInfo)
class ArticleAction(admin.ModelAdmin):

    def func(self, request, queryset):
        queryset.delete()

    func.short_description = "快捷删除选中项"
    actions = [func, ]
    # Action选项都是在页面上方显示
    actions_on_top = True
    # Action选项都是在页面下方显示
    actions_on_bottom = False
    # 是否显示选择个数
    actions_selection_counter = True

admin.site.register(models.Article,ArticleAction)
# 分页,每页显示条数
    list_per_page = 100
 
# 分页,显示全部(真实数据<该值时,才会有显示全部)
    list_max_show_all = 200
 
# 分页插件
    paginator = Paginator
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    date_hierarchy = 'ctime'
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.
class UserInfoInline(admin.StackedInline): # TabularInline
    extra = 0
    model = models.UserInfo
 
class GroupAdminMode(admin.ModelAdmin):
    list_display = ('id', 'title',)
    inlines = [UserInfoInline, ]
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
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
 
    raw_id_fields = ('FK字段', 'M2M字段',)
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    fields = ('user',)
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    exclude = ('user',)
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    readonly_fields = ('user',)
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    fieldsets = (
        ('基本数据', {
            'fields': ('user', 'pwd', 'ctime',)
        }),
        ('其他', {
            'classes': ('collapse', 'wide', 'extrapretty'),  # 'collapse','wide', 'extrapretty'
            'fields': ('user', 'pwd'),
        }),
    )
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
    filter_vertical = ("m2m字段",) # 或filter_horizontal = ("m2m字段",)
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
   ordering = ('-id',)
   或
   def get_ordering(self, request):
       return ['-id', ]
view_on_site = False
或
def view_on_site(self, obj):
    return 'https://www.baidu.com'
radio_fields = {"ug": admin.VERTICAL} # 或admin.HORIZONTAL
@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',)
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},
    }
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
 
    prepopulated_fields = {"email": ("user","pwd",)}

PS: DjangoAdmin中使用js实现功能,页面email字段的值会在输入:user、pwd时自动填充
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
@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 = "指定列数据为空时,默认显示"
上一篇下一篇

猜你喜欢

热点阅读