一、面向对象复习
1、类的继承
class Base(object): def __init__(self,val): self.val = val</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> func(self): self.test() </span><span style="color: #0000ff;">print</span><span style="color: #000000;">(self.val) </span><span style="color: #0000ff;">def</span><span style="color: #000000;"> test(self): </span><span style="color: #0000ff;">print</span>(<span style="color: #800000;">"</span><span style="color: #800000;">Base.test</span><span style="color: #800000;">"</span><span style="color: #000000;">)
class Foo(Base):
def test(self):
print("FOO.test")</span><span style="color: #008000;">#</span><span style="color: #008000;"> def func(self):</span> <span style="color: #008000;">#</span><span style="color: #008000;"> print(self.val,666)</span> <span style="color: #008000;">#</span><span style="color: #008000;">有就执行自己的,没有就执行父类的</span>
class Bar(object):
def init(self):
self._register = {}obj = Bar() #实例化就会去执行它自己的__init__方法,并获取到一个对象b,b就可以调用里面的属性和方法了 obj.regiter(1,Foo) obj.regiter(2) print(obj._register) #{1: <__main__.Foo object at 0x0000000002213160>, 2: <__main__.Base object at 0x0000000002213198>} #obj._register[1] == Foo(1) obj._register[1].func() #Foo的对象 打印结果:FOO.test 1 obj._register[2].func() #Base的对象 打印结果:Base.test 2</span><span style="color: #0000ff;">def</span> regiter(self,a,b=<span style="color: #000000;">None): </span><span style="color: #0000ff;">if</span> <span style="color: #0000ff;">not</span><span style="color: #000000;"> b: b</span>=<span style="color: #000000;">Base self._register[a] </span>= b(a) <span style="color: #008000;">#</span><span style="color: #008000;">函数,类,对象</span>
2、单例模式:单例模式是一个设计模式(说白了就是单个实例公用一个对象)
举例一:
s1.py
class Foo(object): def test(self): print("123")v = Foo()
#v是Foo的实例
s2.py
from s1 import v as v1 print(v1,id(v1)) #<s1.Foo object at 0x0000000002221710> 35788560from s1 import v as v2
print(v1,id(v2)) #<s1.Foo object at 0x0000000002221710> 35788560# 两个的内存地址是一样的
文件加载的时候,第一次导入后,再次导入时不会再重新加载。
举例二:
class Singleton: def __new__(cls, *args, **kw): '''__new__是一个构造方法,self就是他构造的''' if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kw) return cls._instanceone = Singleton()
two = Singleton()
print(one,two) #他们两个的地址一样print(id(one),id(two))
one.name = 'alex'
print(two.name)
二、django-admin的简单回顾
1、admin
a:models.py
- 创建表
b:admin.py
- 注册表 admin.site.register(models.UserInfo)
c:urls.py
- url(r'^admin/', admin.site.urls),
PS:
1、动态生成url
2、注册和生成url使用的都是admin.site
2、路由系统
一个路径对应一个视图
url(r'^index/$', views.index,name="n1"),
url(r'^index/(d+)$', views.index,name="n2"), url(r'^blog/', include('blog.urls'))
有name的说明是反向解析,两种方式
代码中:
reverse('n1')
reverse('n2',args=(666,))
模板中:
{% url 'n1' %}
{% url 'n2' 666 %}
3、文件加载
第一次导入后,再次导入时不再重新加载
4、面向对象
- 封装
- 继承
示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Base(object): 2 def __init__(self,val): 3 self.val = val 4 5 def func(self): 6 self.test() 7 print(self.val) 8 9 def test(self): 10 print("Base.test") 11 12 class Foo(Base): 13 def test(self): 14 print("FOO.test") 15 16 # def func(self): 17 # print(self.val,666) 18 #有就执行自己的,没有就执行父类的 19 class Bar(object): 20 def __init__(self): 21 self._register = {} 22 23 def regiter(self,a,b=None): 24 if not b: 25 b=Base 26 self._register[a] = b(a) #函数,类,对象 27 28 obj = Bar() #实例化就会去执行它自己的__init__方法,并获取到一个对象b,b就可以调用里面的属性和方法了 29 obj.regiter(1,Foo) 30 obj.regiter(2) 31 print(obj._register) #{1: <__main__.Foo object at 0x0000000002213160>, 2: <__main__.Base object at 0x0000000002213198>} 32 #obj._register[1] == Foo(1) 33 obj._register[1].func() #Foo的对象 打印结果:FOO.test 1 34 obj._register[2].func() #Base的对象 打印结果:Base.test 2
三、具体来说django -admin的用法
首先需要发现的,当我们创建登录admin的时候,里面会有增删改查,不仅仅是这些功能,我们可以通过以下的方式设置一些样式
1、admin路由规则:
/admin/app01/role/ 查看角色列表 /admin/app01/role/add/ 添加角色 /admin/app01/role/2/change/ 编辑 /admin/app01/role/2/delete/ 删除/admin/app01/userinfo/ /admin/应用名/表名
/admin/app01/userinfo/add/ /admin/应用名/表名/功能名
/admin/app01/userinfo/1/change/ /admin/app01/userinfo/1/delete/
2、如何使用之具体操作:http://www.cnblogs.com/wupeiqi/articles/7444717.html
3、原理:
- 路由关系
- 对应视图函数
admin的使用
自定制admin
首先创建表:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from django.db import models 2 class UserInfo(models.Model): 3 name = models.CharField(max_length=32,verbose_name="用户名") 4 email = models.EmailField(max_length=32,verbose_name="邮箱") 5 ut = models.ForeignKey(to="UserType",verbose_name="所属类型") 6 7 8 class UserType(models.Model): 9 caption = models.CharField(max_length=32,verbose_name="用户类型名称") 10 roles = models.ManyToManyField(to="Role",verbose_name="所属角色") 11 12 class Role(models.Model): 13 name = models.CharField(max_length=32,verbose_name="角色名")
1、在admin.py中只需要讲Mode中的某个类注册,即可在Admin中实现增删改查的功能,如:
admin.site.register(models.UserInfo)
admin.site.register(models.Role)
admin.site.register(models.UserType)
2、创建超级用户,刚登录上的时候
3、我们要把我们自己的表名改成中文的和吧对象变成中文的:
class Meta: verbose_name_plural = "用户表"<span style="color: #0000ff;">def</span> <span style="color: #800080;">__str__</span><span style="color: #000000;">(self): </span><span style="color: #0000ff;">return</span> self.name</pre>
但是,这种方式比较简单,如果想要进行更多的定制操作,需要利用ModelAdmin进行操作,如:
方式一: class UserAdmin(admin.ModelAdmin): list_display = ('user', 'pwd',)admin.site.register(models.UserInfo, UserAdmin) </span><span style="color: #008000;">#</span><span style="color: #008000;"> 第一个参数可以是列表</span>
方式二:
@admin.register(models.UserInfo) # 第一个参数可以是列表
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd',)
ModelAdmin中提供了大量的可定制功能,如
1. list_display,列表时,定制显示的列。
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): list_display = ('user', 'pwd', 'xxxxx')</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> xxxxx(self, obj): </span><span style="color: #0000ff;">return</span> <span style="color: #800000;">"</span><span style="color: #800000;">xxxxx</span><span style="color: #800000;">"<br> #或者<br> return obj.name +"最漂亮"</span></pre>
2. list_display_links,列表时,定制列可以点击跳转。
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): list_display = ('user', 'pwd', 'xxxxx') list_display_links = ('pwd',)
3. list_filter,列表时,定制右侧快速筛选。
from django.utils.translation import ugettext_lazy as _@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd')</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> Ugg(admin.SimpleListFilter): title </span>= _(<span style="color: #800000;">'</span><span style="color: #800000;">decade born</span><span style="color: #800000;">'</span><span style="color: #000000;">) parameter_name </span>= <span style="color: #800000;">'</span><span style="color: #800000;">xxxxxx</span><span style="color: #800000;">'</span> <span style="color: #0000ff;">def</span><span style="color: #000000;"> lookups(self, request, model_admin): </span><span style="color: #800000;">"""</span><span style="color: #800000;"> 显示筛选选项 :param request: :param model_admin: :return: </span><span style="color: #800000;">"""</span> <span style="color: #0000ff;">return</span> models.UserGroup.objects.values_list(<span style="color: #800000;">'</span><span style="color: #800000;">id</span><span style="color: #800000;">'</span>, <span style="color: #800000;">'</span><span style="color: #800000;">title</span><span style="color: #800000;">'</span><span style="color: #000000;">) </span><span style="color: #0000ff;">def</span><span style="color: #000000;"> queryset(self, request, queryset): </span><span style="color: #800000;">"""</span><span style="color: #800000;"> 点击查询时,进行筛选 :param request: :param queryset: :return: </span><span style="color: #800000;">"""</span><span style="color: #000000;"> v </span>=<span style="color: #000000;"> self.value() </span><span style="color: #0000ff;">return</span> queryset.filter(ug=<span style="color: #000000;">v) list_filter </span>= (<span style="color: #800000;">'</span><span style="color: #800000;">user</span><span style="color: #800000;">'</span>,Ugg,)</pre>
4、search_field:添加搜索框
5、action,列表时,定制action中的操作
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin):</span><span style="color: #008000;">#</span><span style="color: #008000;"> 定制Action行为具体方法</span> <span style="color: #0000ff;">def</span><span style="color: #000000;"> func(self, request, queryset): </span><span style="color: #0000ff;">print</span><span style="color: #000000;">(self, request, queryset) </span><span style="color: #0000ff;">print</span>(request.POST.getlist(<span style="color: #800000;">'</span><span style="color: #800000;">_selected_action</span><span style="color: #800000;">'</span><span style="color: #000000;">)) func.short_description </span>= <span style="color: #800000;">"</span><span style="color: #800000;">中文显示自定义Actions</span><span style="color: #800000;">"</span><span style="color: #000000;"> actions </span>=<span style="color: #000000;"> [func, ] </span><span style="color: #008000;">#</span><span style="color: #008000;"> Action选项都是在页面上方显示</span> actions_on_top =<span style="color: #000000;"> True </span><span style="color: #008000;">#</span><span style="color: #008000;"> Action选项都是在页面下方显示</span> actions_on_bottom =<span style="color: #000000;"> False </span><span style="color: #008000;">#</span><span style="color: #008000;"> 是否显示选择个数</span> actions_selection_counter = True</pre>
5、 list_select_related,列表时,连表查询是否自动select_related
6. 分页相关
# 分页,每页显示条数 list_per_page = 100# 分页,显示全部(真实数据<该值时,才会有显示全部)
list_max_show_all = 200# 分页插件
paginator = Paginator
7、 list_editable,列表时,可以编辑的列
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): list_display = ('user', 'pwd','ug',) list_editable = ('ug',)
8、search_fields,列表时,模糊搜索的功能
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin):search_fields </span>= (<span style="color: #800000;">'</span><span style="color: #800000;">user</span><span style="color: #800000;">'</span>, <span style="color: #800000;">'</span><span style="color: #800000;">pwd</span><span style="color: #800000;">'</span>)</pre>
9、date_hierarchy,列表时,对Date和DateTime类型进行搜索
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin):date_hierarchy </span>= <span style="color: #800000;">'</span><span style="color: #800000;">ctime</span><span style="color: #800000;">'</span></pre>
10、preserve_filters,详细页面,删除、修改,更新后跳转回列表后,是否保留原搜索条件
11、save_as = False,详细页面,按钮为“Sava as new” 或 “Sava and add another”
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 UserInfoInline(admin.StackedInline): # TabularInline extra = 0 model = models.UserInfoclass GroupAdminMode(admin.ModelAdmin):
list_display = ('id', 'title',)
inlines = [UserInfoInline, ]
14、定制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
15、raw_id_fields,详细页面,针对FK和M2M字段变成以Input框形式
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin):raw_id_fields </span>= (<span style="color: #800000;">'</span><span style="color: #800000;">FK字段</span><span style="color: #800000;">'</span>, <span style="color: #800000;">'</span><span style="color: #800000;">M2M字段</span><span style="color: #800000;">'</span>,)</pre>
16、 fields,详细页面时,显示字段的字段
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): fields = ('user',)
18. exclude,详细页面时,排除的字段
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): exclude = ('user',)
19. readonly_fields,详细页面时,只读字段
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): readonly_fields = ('user',)
20. fieldsets,详细页面时,使用fieldsets标签对数据进行分割显示
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): fieldsets = ( ('基本数据', { 'fields': ('user', 'pwd', 'ctime',) }), ('其他', { 'classes': ('collapse', 'wide', 'extrapretty'), # 'collapse','wide', 'extrapretty' 'fields': ('user', 'pwd'), }), )
21. 详细页面时,M2M显示时,数据移动选择(方向:上下和左右)
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): filter_vertical = ("m2m字段",) # 或filter_horizontal = ("m2m字段",)
22. ordering,列表时,数据排序规则
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): ordering = ('-id',) 或 def get_ordering(self, request): return ['-id', ]
23. view_on_site,编辑时,是否在页面上显示view on set
view_on_site = False 或 def view_on_site(self, obj): return 'https://www.baidu.com'
24. radio_fields,详细页面时,使用radio显示选项(FK默认使用select)
radio_fields = {"ug": admin.VERTICAL} # 或admin.HORIZONTAL
25. show_full_result_count = True,列表时,模糊搜索后面显示的数据个数样式
@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',)
26. formfield_overrides = {},详细页面时,指定现实插件
from django.forms import widgets from django.utils.html import format_htmlclass 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)</span><span style="color: #0000ff;">def</span> render(self, name, value, attrs=<span style="color: #000000;">None): </span><span style="color: #0000ff;">if</span> value <span style="color: #0000ff;">is</span><span style="color: #000000;"> None: value </span>= <span style="color: #800000;">''</span><span style="color: #000000;"> final_attrs </span>= self.build_attrs(attrs, name=<span style="color: #000000;">name) </span><span style="color: #0000ff;">return</span> format_html(<span style="color: #800000;">'</span><span style="color: #800000;"><textarea {}> {}</textarea></span><span style="color: #800000;">'</span><span style="color: #000000;">,final_attrs, value)
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):formfield_overrides </span>=<span style="color: #000000;"> { models.models.CharField: {</span><span style="color: #800000;">'</span><span style="color: #800000;">widget</span><span style="color: #800000;">'</span><span style="color: #000000;">: MyTextarea}, }</span></pre>
27. prepopulated_fields = {},添加页面,当在某字段填入值后,自动会将值填充到指定字段。
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin):prepopulated_fields </span>= {<span style="color: #800000;">"</span><span style="color: #800000;">email</span><span style="color: #800000;">"</span>: (<span style="color: #800000;">"</span><span style="color: #800000;">user</span><span style="color: #800000;">"</span>,<span style="color: #800000;">"</span><span style="color: #800000;">pwd</span><span style="color: #800000;">"</span>,)}</pre>
PS: DjangoAdmin中使用js实现功能,页面email字段的值会在输入:user、pwd时自动填充
28. form = ModelForm,用于定制用户请求时候表单验证
from app01 import models from django.forms import ModelForm from django.forms import fieldsclass MyForm(ModelForm):
others = fields.CharField()</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> Meta: model </span>= models =<span style="color: #000000;"> models.UserInfo fields </span>= <span style="color: #800000;">"</span><span style="color: #800000;">__all__</span><span style="color: #800000;">"</span><span style="color: #000000;">
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):form </span>= MyForm</pre>
29. empty_value_display = "列数据为空时,显示默认值"
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): empty_value_display = "列数据为空时,默认显示"list_display </span>= (<span style="color: #800000;">'</span><span style="color: #800000;">user</span><span style="color: #800000;">'</span>,<span style="color: #800000;">'</span><span style="color: #800000;">pwd</span><span style="color: #800000;">'</span>,<span style="color: #800000;">'</span><span style="color: #800000;">up</span><span style="color: #800000;">'</span><span style="color: #000000;">) </span><span style="color: #0000ff;">def</span><span style="color: #000000;"> up(self,obj): </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> obj.user up.empty_value_display </span>= <span style="color: #800000;">"</span><span style="color: #800000;">指定列数据为空时,默认显示</span><span style="color: #800000;">"</span></pre>
简单测试admin示例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)