search
HomeBackend DevelopmentPython TutorialAnalysis of Django admin source code (with examples)

The content of this article is about the analysis of Django admin source code (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Singleton Pattern

Singleton Pattern is a commonly used software design pattern. The main purpose of this pattern is to ensure that only one instance of a certain 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, which will seriously waste memory resources. , especially when 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:

  • Use __new__()

  • Use module

  • Use decorator

  • Use metaclass

1. Use __new__() method

In order to make only one instance of the class appear, we can use __new__() to control the creation process of the instance. The code is as follows:

__new__() method is used to create instance objects

__init__() method is used to initialize instance objects

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
class Singleton(object):
    _instance = None

    def __new__(cls, *args, **kwargs):
        print(1)
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

    def __init__(self, name, age):
        print(2)
        self.name = name
        self.age = age
if __name__ == '__main__':
    p1 = Person("djb", 18)
    p2 = Person("djb", 18)

    print(p1 == p2)
    print(id(p1), id(p2))

    print("=" * 120)

    s1 = Singleton("djb", 18)
    s2 = Singleton("djb", 18)
    print(s1 == s2)
    print(id(s1), id(s2))

2. Use module method

In fact, Python modules are Natural singleton mode, because when the module is imported for the first time, a .pyc file will be generated. When it is imported for the second time, the .pyc file will be loaded directly without executing the module code again. Therefore, we only need to define the relevant functions and data in a module to get a singleton object.

If we really want a singleton class, we can consider doing this:

class Singleton(object):    
def __init__(self, name, age):
        self.name = name
        self.age = age
p1 = Singleton("djb", 18)

Use the following code to test it:

from singleton import p1

print(id(p1))
print(p1.name)
p1.name = "Bob"

from singleton import p1

print(id(p1))
print(p1.name)

Check the remaining two types yourself Information...

admin execution process

Cycle loading and execution of the admin.py files in all registered apps

def autodiscover():
    autodiscover_modules('admin', register_to=site)

Execution Code

#admin.py
class BookAdmin(admin.ModelAdmin):
    list_display = ("title",'publishDate', 'price')
admin.site.register(Book, BookAdmin) 
admin.site.register(Publish)

admin.site

##What is applied here is a singleton mode. For a singleton mode of the AdminSite class, the execution Each admin.site in each app is an object

Execute the register method

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)

Here, registration is over!

Admin’s URL configuration

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
    @property
    def urls(self):
        return self.get_urls(), 'admin', self.name

Extension application of url() method

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'^Xadmin/', ([
                    url(r'^test01/', test01),
                    url(r'^test02/', test02),

                    ],None,None)),
]

Extension optimization

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'^Xadmin/', (url_list,None,None)),
]

The above is the detailed content of Analysis of Django admin source code (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool