Home > Backend Development > Python Tutorial > Detailed explanation of the use and source code analysis of Django's admin component

Detailed explanation of the use and source code analysis of Django's admin component

不言
Release: 2018-05-04 14:26:59
Original
1742 people have browsed it

This article mainly introduces the use and source code analysis of Django's admin component. It has certain reference value. Now I share it with you. Friends in need can refer to

admin component Using

Django provides web-based management tools.

Django automatic management tools are part of django.contrib. You can see it in INSTALLED_APPS in the project's settings.py:

# Application definition

INSTALLED_APPS = [
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
  "app01"
]
Copy after login

django.contrib is a huge feature set that is the Django base code Part.

Activation management tool

Usually we will automatically set it in urls.py when generating the project,

from django.conf.urls import url
from django.contrib import admin

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

]
Copy after login

When this is all configured, the Django management tool is ready to run.

Use management tools

Start the development server, and then visit http://127.0.0.1:8000/admin/ in the browser to get the login interface. You can Create a superuser through the command python manage.py createsuperuser.

In order for the admin interface to manage a certain data model, we need to first register the data model to the admin

from django.db import models

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
Copy after login

Customization of admin

In admin.py, you only need to register a certain class in Mode to realize the function of adding, deleting, modifying and checking in Admin, such as:

admin.site.register(models.UserInfo)
Copy after login

However, this method is relatively simple. If you want to perform more customization operations, you need to use ModelAdmin to operate, such as:

Method 1:

class UserAdmin(admin.ModelAdmin):
   list_display = ('user', 'pwd',)
 
admin.site.register(models.UserInfo, UserAdmin) # 第一个参数可以是列表
Copy after login

Method 2:

@admin.register(models.UserInfo)        # 第一个参数可以是列表
class UserAdmin(admin.ModelAdmin):
  list_display = ('user', 'pwd',)
Copy after login

ModelAdmin provides a large number of customizable functions. Such as

1. list_display, when listing, customize the displayed columns.

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

2. list_display_links, when listing, you can click to jump to customized columns.

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

3. list_filter, when listing, customize the quick filter on the right side.

4. list_select_related, when making a list, whether the join table query will automatically select_related

5. list_editable, when making a list, the columns that can be edited

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

6. search_fields, fuzzy search function when using a list

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

7. date_hierarchy, searching for Date and DateTime types when using a list

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

8 inlines, detailed page, if there are other tables doing FK with the current table, then the detailed page can be dynamically added and deleted

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

9 action, in the list, customize the operations in the 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
Copy after login

10 Customize the HTML template

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
Copy after login

11 raw_id_fields, detailed page, for FK and M2M fields become Input box form

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

12 fields, on the detailed page, the fields of the displayed fields

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

13 exclude, on the detailed page, the excluded fields

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

14 readonly_fields, on the detailed page, read-only fields

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

##15 fieldsets, on the detailed page, use the fieldsets tag Data is divided and displayed

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
  fieldsets = (
    ('基本数据', {
      'fields': ('user', 'pwd', 'ctime',)
    }),
    ('其他', {
      'classes': ('collapse', 'wide', 'extrapretty'), # 'collapse','wide', 'extrapretty'
      'fields': ('user', 'pwd'),
    }),
  )
Copy after login

16 When displaying the detailed page and M2M, data movement selection (direction: up, down and left and right)

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

17 ordering, data sorting rules when listing,

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

18. radio_fields, when using detailed pages, use radio display Options (FK uses select by default)

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

19 form = ModelForm, used to customize form validation when user requests

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
Copy after login

20 empty_value_display = "When the column data is empty, display the default value"

@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 = "指定列数据为空时,默认显示"
Copy after login

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)
Copy after login

admin source code analysis

Single case pattern

Singleton Pattern is a commonly used software design pattern. The main purpose of this pattern is Ensure that only one instance of a class exists. Singleton objects come in handy when you want only one instance of a certain class to appear in the entire system.

For example, the configuration information of a server program is stored in a file, and the client reads the configuration file information through an AppConfig class. If the contents of the configuration file need to be used in many places during the running of the program, that is to say, instances of the AppConfig object need to be created in many places, which will lead to the existence of multiple AppConfig instance objects in the system, and this will seriously waste memory. resources, especially if the configuration file contains a lot of content. In fact, for a class like AppConfig, we hope that only one instance object exists while the program is running.

In Python, we can use a variety of methods to implement the singleton pattern:

  1. Use modules

  2. Use __new__

  3. Use decorator

  4. Use metaclass

(1 ) using __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
Copy after login

在上面的代码中,我们将类的实例和一个类变量 _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()
Copy after login

将上面的代码保存在文件 mysingleton.py 中,然后这样使用:

from mysingleton import my_singleton
my_singleton.foo()
Copy after login

admin执行流程

<1> 循环加载执行所有已经注册的app中的admin.py文件

def autodiscover():
  autodiscover_modules(&#39;admin&#39;, register_to=site)
Copy after login

<2> 执行代码

#admin.py
class BookAdmin(admin.ModelAdmin):
  list_display = ("title",&#39;publishDate&#39;, &#39;price&#39;)

admin.site.register(Book, BookAdmin) 
admin.site.register(Publish)
Copy after login

<3> admin.site

这里应用的是一个单例模式,对于AdminSite类的一个单例模式,执行的每一个app中的每一个admin.site都是一个对象

<4> 执行register方法

admin.site.register(Book, BookAdmin) 
admin.site.register(Publish)
Copy after login

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)
Copy after login

到这里,注册结束!

<5> admin的URL配置

urlpatterns = [
  url(r&#39;^admin/&#39;, admin.site.urls),
]
Copy after login

class AdminSite(object):  
   def get_urls(self):
    from django.conf.urls import url, include   
    urlpatterns = []
    # Add in each model&#39;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&#39;^%s/%s/&#39; % (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
  @property
  def urls(self):
    return self.get_urls(), &#39;admin&#39;, self.name
Copy after login

<6> url()方法的扩展应用

from django.shortcuts import HttpResponse
def test01(request):
  return HttpResponse("test01")

def test02(request):
  return HttpResponse("test02")

urlpatterns = [
  url(r&#39;^admin/&#39;, admin.site.urls),
  url(r&#39;^yuan/&#39;, ([
          url(r&#39;^test01/&#39;, test01),
          url(r&#39;^test02/&#39;, test02),

          ],None,None)),

]
Copy after login

扩展优化

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&#39;^admin/&#39;, admin.site.urls),
  url(r&#39;^yuan/&#39;, (url_list,None,None)),
]
Copy after login

仿admin的url路径分发

#############models.py###########
from django.db import models
class Book(models.Model):
  title = models.CharField(max_length=32)
  author = models.ForeignKey(to=&#39;Author&#39;)
class Author(models.Model):
  name = models.CharField(max_length=32)
#################admin.py###########
from app01.models import *
admin.site.register(Book)
admin.site.register(Author)
##############views.py################
from django.shortcuts import HttpResponse
def add(request):
  return HttpResponse(&#39;add&#39;)
def change(request,id):
  return HttpResponse(&#39;change&#39;)
def delete(request,id):
  return HttpResponse(&#39;delete&#39;)
def show(request):
  return HttpResponse(&#39;show&#39;)
################url.py##############
def get_urls2():
  tmp = []
  tmp.append(url(r&#39;^add/&#39;,add))
  tmp.append(url(r&#39;^(\d+)/change/&#39;,change))
  tmp.append(url(r&#39;^(\d+)/delete/&#39;,delete))
  tmp.append(url(r&#39;^&#39;,show))
  return tmp
def get_urls():
  temp = []
  for model, admin_class_obj in admin.site._registry.items():
    model_name = model._meta.model_name
    app_label = model._meta.app_label
    temp.append(url(r&#39;^{}/{}/&#39;.format(app_label,model_name),(get_urls2(),None,None))) #[url(r&#39;^app01/book/&#39;,),]
  return temp

urlpatterns = [
  url(r&#39;^admin/&#39;, (get_urls(), None, None)),
  url(r&#39;^admin/&#39;, admin.site.urls),
]
Copy after login

The above is the detailed content of Detailed explanation of the use and source code analysis of Django's admin component. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template