您的位置:首页 > 编程语言 > Go语言

Django-admin管理工具

2018-03-19 14:23 579 查看

一、Django admin组件使用

  Django提供了基于web的管理工具:amdin组件。

  admin可以对注册完的数据进行增删改成操作。

  一、项目的配置文件(settings.py)相关配置

  Django自动管理工具是django.contrib的一部分。你可以在Django项目的settings.py中INSTALLED_APPS 看到

# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config',
]

  django.contrib是一套庞大的功能集,它是Django基本代码的组成部分。

  创建完django项目注意更改settings.py(注释最后一行)

'DIRS': [os.path.join(BASE_DIR,  'templates')],

  二、激活管理工具(urls.py)

  通常我们在生成项目时,会在urs.py中自动设定好

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

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

]

  三、使用管理工具

  1、创建管理用户,登录验证

  你可以通过命令 python manage.py createsuperuser 来创建超级用户。(也可创建普通用户)

  启动开发服务器,然后在浏览器中访问http://127.0.0.1:8000/admin/,得到登陆界面。

  

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)
admin.py

二、admin源码解析

  一、单例模式

  1、单例模式基本介绍

  单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。

  比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息。如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪费内存资源,尤其是在配置文件内容很多的情况下。事实上,类似 AppConfig 这样的类,我们希望在程序运行期间只存在一个实例对象。

  2、在 Python 中,我们可以用多种方法来实现单例模式:

  • 使用模块
  • 使用 
    __new__
  • 使用装饰器(decorator)
  • 使用元类(metaclass)
    1、使用__new__

  为了使类只能出现一个实例,我们可以使用__new__来控制实例的创建过程,代码如下

class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance

class MyClass(Singleton):
a = 1

one = MyClass()

two = MyClass()
one == two

print one is two                        #True
print ("id_one:",id(one),"id_two:",id(two))   #('id_one:', 78304144L, 'id_two:', 783041

  将类的实例和一个类的变量_instance关联起来,若cls._instance为None则创建实例,否则直接返回cls._instance

    2、使用模块

  Python模块就是天然的单例模式,因为模块在第一次导入时,会生成一个.pyc文件;当第二次导入时,就会直接加载.pyc文件,而不会再次执行模块代码。

  因此,我们只需将相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。

#mysingleton.py
class MySingleton(object):
def foo(self):
pass

my_singleton = MySingleton()

  导入模块

from mysingleton import my_singleton

my_singleton.foo()

  二、admin执行流程

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

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

  2、执行代码

#admin.py

class BookAdmin(admin.ModelAdmin):
list_display = ("title",'publishDate', 'price')

admin.site.register(Book, BookAdmin)
admin.site.register(Publish)

  3、admin.site site.py

class AdminSite(object):
"""
An AdminSite object encapsulates an instance of the Django admin application, ready
to be hooked in to your URLconf. Models are registered with the AdminSite using the
register() method, and the get_urls() method can then be used to access Django view
functions that present a full admin interface for the collection of registered
models.
"""
......................................................
def register(self, model_or_iterable, admin_class=None, **options):
"""
Registers the given model(s) with the given admin class.

The model(s) should be Model classes, not instances.

If an admin class isn't given, it will use ModelAdmin (the default
admin options). If keyword arguments are given -- e.g., list_display --
they'll be applied as options to the admin class.

If a model is already registered, this will raise AlreadyRegistered.

If a model is abstract, this will raise ImproperlyConfigured.
"""
if not admin_class:
admin_class = ModelAdmin
......................................................
# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site.
site = AdminSite()

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

  4、ModelAdmin(GeoModelAdmin) options.py

class GeoModelAdmin(ModelAdmin):
"""
The administration options class for Geographic models. Map settings
may be overloaded from their defaults to create custom maps.
"""

  5、执行register方法

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)

  思考:在每一个app的admin .py中加上

print(admin.site._registry)   # 执行结果?

  6、admin的URL配置

  项目的urls.py文件

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

  7、url()方法的扩展应用

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

],None,None)),

]

  扩展优化

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

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: