Django-Admin

Posted _慕

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django-Admin相关的知识,希望对你有一定的参考价值。

Admin

1.admin大致流程
技术分享图片
admin.py中:
    from django.contrib import admin
    from app01 import models
    admin.site.register(models.UserInfo,admin.ModelAdmin)
    admin.site.register(models.UserGroup,admin.ModelAdmin)
    等同于
    from django.contrib import admin
    from app01 import models
    admin.site.register(models.UserInfo)
    admin.site.register(models.UserGroup)
    等同于
    from django.contrib import admin
    from app01 import models
    #列表之后有没有admin.ModelAdmin都可以,因为默认值就是admin.ModelAdmin
    admin.site.register([models.UserInfo,models.UserGroup])

admin.py是在python manage.py runserver 时,自动调用所有app中的admin.py:
    admin.site.register中的register其实写的是下面的这个
        _registry = {
            models.UserInfo: admin.ModelAdmin(models.UserInfo,admin.site)
            models.UserGroup: admin.ModelAdmin(models.UserGroup,admin.site)
        }
    执行manage.py时加载配置文件    
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "s4day119.settings")
        
        settings.py中:
            ROOT_URLCONF = s4day119.urls
        urls.py:
            url(r^admin/, admin.site.urls),
            进入.urls
            def urls(self):
                return self.get_urls(), admin, self.name
            进入self.get_urls()中
                admin.site.register中的register其实写的是下面的这个
                #_registry = {
                #    models.UserInfo: admin.ModelAdmin(models.UserInfo,admin.site)
                #    models.UserGroup: admin.ModelAdmin(models.UserGroup,admin.site)
                #}
                # model._meta.app_label拿到表名所对应的APP名,model._meta.model_name拿到表名
                #url(r‘^%s/%s/‘ 第一个%s改成了APP名称,第二个%s改成表名
                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)),
                        app01/userinfo/
                    ]
                    if model._meta.app_label not in valid_app_labels:
                        valid_app_labels.append(model._meta.app_label)
                        
            for item in model_class_list:
                item获取app名称,表名称
                http://127.0.0.1:8001/admin/app名称/表名称/             - 数据列表
                http://127.0.0.1:8001/admin/app01/userinfo/add/         - 添加数据
                http://127.0.0.1:8001/admin/app01/userinfo/1/change/ - 修改数据
                http://127.0.0.1:8001/admin/app01/userinfo/1/delete/ - 删除数据
流程
2.定制admin

    -1.在admin中注册表名

admin.py中:
	from django.contrib import admin
	from app01 import models
	admin.site.register(models.UserInfo,admin.ModelAdmin)
	admin.site.register(models.UserGroup,admin.ModelAdmin)
	等同于
	from django.contrib import admin
	from app01 import models
	admin.site.register(models.UserInfo)
	admin.site.register(models.UserGroup)
	等同于
	from django.contrib import admin
	from app01 import models
	#列表之后有没有admin.ModelAdmin都可以,因为默认值就是admin.ModelAdmin
	admin.site.register([models.UserInfo,models.UserGroup])

    -2.定制操作

方式一:
	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‘,)	
3.ModelAdmin中提供了大量的可定制功能:

    -1. list_display,列表时,定制显示的列。

class UserInfoModelAdmin(admin.ModelAdmin):
    def New_Column(self, obj):
	return "New_Column"
    list_display = (‘user‘, ‘pwd‘,‘New_Column‘)
    #‘user‘, ‘pwd‘是数据库查到的字段,New_Column是自定制要显示的列,显示什么内容都可以
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -2. list_display_links,列表时,定制列可以点击跳转 (默认是第一列) 

from django.utils.safestring import mark_safe	
class UserInfoModelAdmin(admin.ModelAdmin):
    def New_Column(obj):
	return mark_safe("<a href=‘http://www.baidu.com‘>%s</a>" % (obj.user,))
    list_display = (‘user‘, ‘pwd‘,‘New_Column‘)
    list_display_links = (‘pwd‘,)  #默认时 点击user列会跳转,现在是点击pwd列会跳转
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -3.list_filter,列表时,定制右侧快速筛选。 

from django.utils.safestring import mark_safe	
class UserInfoModelAdmin(admin.ModelAdmin):
    def New_Column(obj):
	return mark_safe("<a href=‘http://www.baidu.com‘>%s</a>" % (obj.user,))
    list_display = (‘user‘, ‘pwd‘,‘New_Column‘)
    list_display_links = (‘pwd‘,)  #默认时 点击user列会跳转,现在是点击pwd列会跳转
    list_filter = (‘user‘,‘email‘)
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -4.list_select_related,列表时,连表查询是否自动select_related

   -5. 分页相关 

# 分页,每页显示条数
    list_per_page = 100
  
# 分页,显示全部(真实数据<该值时,才会有显示全部)
    list_max_show_all = 200
  
# 分页插件
    paginator = Paginator

    -6. list_editable,列表时,可以编辑的列

class UserInfoModelAdmin(admin.ModelAdmin):
    list_display = (‘user‘, ‘pwd‘,)

    list_editable = (‘user‘,))
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

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

class UserInfoModelAdmin(admin.ModelAdmin):
    list_display = (‘user‘, ‘pwd‘,)

    search_fields = (‘user‘, ‘pwd‘)
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -8.date_hierarchy,列表时,对Date和DateTime类型进行搜索

class UserInfoModelAdmin(admin.ModelAdmin):
    list_display = (‘user‘, ‘pwd‘,)

    date_hierarchy = ‘ctime‘  # 表中要有相应的ctime字段ctime=models.DateTimeField(auto_now_add=True)
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -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 UserInfoModelAdmin(admin.ModelAdmin):
    list_display = (‘user‘, ‘pwd‘,)

    date_hierarchy = ‘ctime‘  # 表中要有相应的ctime字段ctime=models.DateTimeField(auto_now_add=True)
	 
class UserInfoInline(admin.TabularInline):  # TabularInline StackedInline
    extra = 0
    model = models.UserInfo

class UserGroupModelAdmin(admin.ModelAdmin):
    list_display = (‘id‘, ‘title‘,)
    inlines = [UserInfoInline, ]
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -14. action,列表时,定制action中的操作

class UserInfoModelAdmin(admin.ModelAdmin):
    list_display = (‘user‘, ‘pwd‘,)

	# 定制Action行为具体方法
    def func(self, request, queryset):
        print(self, request, queryset)
        print(request.POST.getlist(‘_selected_action‘))

    func.short_description = "操作"
    actions = [func, ]

    # Action选项都是在页面上方显示
    #actions_on_top = True
    # Action选项都是在页面下方显示
    #actions_on_bottom = False

    # 是否显示选择个数
    #actions_selection_counter = True
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -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框形式

class UserInfoModelAdmin(admin.ModelAdmin):

	raw_id_fields = (‘FK字段‘, ‘M2M字段‘,)
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -17. fields,详细页面时,显示字段的字段

class UserInfoModelAdmin(admin.ModelAdmin):

    fields = (‘user‘,)
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -18. exclude,详细页面时,排除的字段

class UserInfoModelAdmin(admin.ModelAdmin):

    exclude = (‘user‘,)
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -19. readonly_fields,详细页面时,只读字段

class UserInfoModelAdmin(admin.ModelAdmin):

    readonly_fields = (‘user‘,)
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -20.fieldsets,详细页面时,使用fieldsets标签对数据进行分割显示

class UserInfoModelAdmin(admin.ModelAdmin):

    fieldsets = (
        (‘基本数据‘, {
            ‘fields‘: (‘user‘,)
        }),
        (‘其他‘, {
            ‘classes‘: (‘collapse‘, ‘wide‘, ‘extrapretty‘),  # ‘collapse‘,‘wide‘, ‘extrapretty‘
            ‘fields‘: (‘pwd‘,),
        }),
    )
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -21. 详细页面时,M2M显示时,数据移动选择(方向:上下和左右)

class UserInfoModelAdmin(admin.ModelAdmin):

    filter_vertical = (‘m2m‘,)  # 或filter_horizontal = ("m2m字段",)
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -22. ordering,列表时,数据排序规则

class UserInfoModelAdmin(admin.ModelAdmin):

    ordering = (‘-id‘,)
    或
    def get_ordering(self, request):
        return [‘-id‘, ]
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -23. view_on_site 编辑时 是否在页面上显示view on set

class UserInfoModelAdmin(admin.ModelAdmin):

    view_on_site = False
    或
    def view_on_site(self, obj):
        return ‘https://www.baidu.com‘
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -24. radio_fields,详细页面时,使用radio显示选项(FK默认使用select)

class UserInfoModelAdmin(admin.ModelAdmin):

    radio_fields = {"ug": admin.VERTICAL} # 或admin.HORIZONTAL
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -25. show_full_result_count = True 列表时 模糊搜索后面显示的数据个数样式  

class UserInfoModelAdmin(admin.ModelAdmin):

    # show_full_result_count = True # 1 result (12 total)
    # show_full_result_count = False  # 1 result (Show all)
    search_fields = (‘user‘,)
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -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)
		
class UserInfoModelAdmin(admin.ModelAdmin):

    formfield_overrides = {
        models.models.CharField: {‘widget‘: MyTextarea},
    }
	
admin.site.register(models.UserInfo, UserInfoModelAdmin)

    -27. prepopulated_fields = {} 添加页面 当在某字段填入值后 自动会将值填充到指定字段

class UserInfoModelAdmin(admin.ModelAdmin):

    prepopulated_fields = {"email": ("user","pwd",)}
	
admin.site.register(models.UserInfo, UserInfoModelAdmin) 

ModelForm组件

ModelForm
    a.  class Meta:
            model,                           # 对应Model的
            fields=None,                     # 字段
            exclude=None,                    # 排除字段
            labels=None,                     # 提示信息
            help_texts=None,                 # 帮助提示信息
            widgets=None,                    # 自定义插件
            error_messages=None,             # 自定义错误信息(整体错误信息from django.core.exceptions import NON_FIELD_ERRORS)
            field_classes=None               # 自定义字段类 (也可以自定义字段)
            localized_fields=(‘birth_date‘,) # 本地化,如:根据不同时区显示数据
            如:
                数据库中
                    2016-12-27 04:10:57
                setting中的配置
                    TIME_ZONE = ‘Asia/Shanghai‘
                    USE_TZ = True
                则显示:
                    2016-12-27 12:10:57
    b. 验证执行过程
        is_valid -> full_clean -> 钩子 -> 整体错误
 
    c. 字典字段验证
        def clean_字段名(self):
            # 可以抛出异常
            # from django.core.exceptions import ValidationError
            return "新值"
    d. 用于验证
        model_form_obj = XXOOModelForm()
        model_form_obj.is_valid()
        model_form_obj.errors.as_json()
        model_form_obj.clean()
        model_form_obj.cleaned_data
    e. 用于创建
        model_form_obj = XXOOModelForm(request.POST)
        #### 页面显示,并提交 #####
        # 默认保存多对多
            obj = form.save(commit=True)
        # 不做任何操作,内部定义 save_m2m(用于保存多对多)
            obj = form.save(commit=False)
            obj.save()      # 保存单表信息
            obj.save_m2m()  # 保存关联多对多信息
 
    f. 用于更新和初始化
        obj = model.tb.objects.get(id=1)
        model_form_obj = XXOOModelForm(request.POST,instance=obj)
        ...
 
        PS: 单纯初始化
            model_form_obj = XXOOModelForm(initial={...})

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

  

  

  

  

  

  

  

 

以上是关于Django-Admin的主要内容,如果未能解决你的问题,请参考以下文章

解决‘django-admin‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件的问题

django-admin 和django-admin.py的区别

django-admin.py startproject 不工作

autoslugfield 进入 django-admin 界面?

找不到命令:django-admin.py

django-admin:command not found的解决办法