2018-10-16 17:26:44
Django MTV 路由配置里面有 反向解析
参考连接:https://www.cnblogs.com/yuanchenqi/articles/7629939.html
https://www.cnblogs.com/yuanchenqi/articles/7629939.html#_label2
这个就是仿照Django的admin做的! 这是1.0版本,后面还得迭代!
明天开始整理自己博客!这几天一直在看视频!
我觉得温故而习之,可以为师矣!!明天回顾一下整理博客还是很有必要的!
放上stark1.0代码 后期继续优化,等有完整版的放到github里面
strak是创建的新的app,需要在settings里面注册一下
stark/service/stark.py
from django.conf.urls import url
from django.shortcuts import HttpResponse, render
# 超级用户 root root1234 class ModelStark(object):
"""父类默认配置类"""
# 默认为空
list_display = [] def __init__(self, model, site):
self.model = model
self.site = site def add(self, request):
return HttpResponse("add") def delete(self, request, id):
return HttpResponse("delete") def change(self, request, id):
return HttpResponse("change") def list_view(self, request):
data_list = self.model.objects.all() # 【obj1,obj2,....】
new_data_list = []
for obj in data_list:
temp = []
for filed in self.list_display: # ["pk","name","age",edit]
if callable(filed): # 判断循环字段是字符串还是函数
val = filed(self, obj)
else:
val = getattr(obj, filed)
temp.append(val)
new_data_list.append(temp) '''
[
[1,"alex",12], ] '''
return render(request, "list_view.html", locals()) def get_urls_2(self):
"""实现二级分发"""
temp = []
# 通过方法 找到表的名字和 app的名字
model_name = self.model._meta.model_name
app_label = self.model._meta.app_label
# 反向解析,给url起名字,
temp.append(url(r"^add/", self.add, name="%s_%s_add" % (app_label, model_name)))
temp.append(url(r"^(\d+)/delete/", self.delete, name="%s_%s_delete" % (app_label, model_name)))
temp.append(url(r"^(\d+)/change/", self.change, name="%s_%s_change" % (app_label, model_name)))
temp.append(url(r"^$", self.list_view, name="%s_%s_list" % (app_label, model_name))) return temp @property
def urls_2(self):
# 二级分发 和一级分发一样
return self.get_urls_2(), None, None class StarkSite(object):
def __init__(self):
self._registry={} def register(self,model,stark_class=None):
if not stark_class:
stark_class=ModelStark self._registry[model] = stark_class(model, self) def get_urls(self):
"""一级分发"""
temp = []
for model, stark_class_obj in self._registry.items():
model_name = model._meta.model_name
app_label = model._meta.app_label
# 分发增删改查
# stark_class_obj是传入配置类的实例对象,由于该类继承了ModelStark,则解耦直接调用父类方法
temp.append(url(r"^%s/%s/" % (app_label, model_name), stark_class_obj.urls_2)) '''
url(r"^app01/userinfo/",UserConfig(Userinfo).urls_2),
url(r"^app01/book/",ModelStark(Book).urls_2), '''
return temp @property
def urls(self):
# 返回一个([], None, None)
return self.get_urls(), None, None # 创建单例对象
site = StarkSite()
app01/stark.py
from stark.service.stark import site, ModelStark
from django.urls import reverse # 反向解析导入的包
from .models import *
from django.utils.safestring import mark_safe # 防止转译 class UserConfig(ModelStark):
"""UserInfo的表的配置类"""
def edit(self, obj):
# return mark_safe("<a href='%s/change'>编辑</a>"%obj.pk)
model_name = self.model._meta.model_name
app_label = self.model._meta.app_label
# 反向解析如果需要传参(带正则),则必须传参
_url = reverse("%s_%s_change"%(app_label,model_name),args=(obj.pk,))
print("_url", _url)
return mark_safe("<a href='%s'>编辑</a>"%_url) def deletes(self, obj):
# return mark_safe("<a href='%s/change'>编辑</a>"%obj.pk)
model_name = self.model._meta.model_name
app_label = self.model._meta.app_label
_url = reverse("%s_%s_delete" % (app_label, model_name), args=(obj.pk,))
print("_url", _url)
return mark_safe("<a href='%s'>删除</a>" % _url) def checkbox(self, obj):
return mark_safe('<input type="checkbox">')
list_display = [checkbox, "pk", "name", "age", edit, deletes] site.register(UserInfo, UserConfig) class BookConfig(ModelStark):
list_display = ["pk", "title"] site.register(Book)
urls.py
from django.conf.urls import url
from django.contrib import admin
from stark.service.stark import site urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^stark/', site.urls),
]
app01/models.py
from django.db import models class UserInfo(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField() def __str__(self):
return self.name class Book(models.Model):
title = models.CharField(max_length=32) def __str__(self):
return self.title
里面有注释,按照流程一步一步走,还是很清楚!
Django的admin做的最好的就是通过类来解耦,降低耦合性!!!!这篇是昨天的迭代,增加部分views东西!有不懂的可以看昨天的博客!
放上笔记!
上节回顾 1 admin的使用
list_display
list_display_links
search_fields
list_filter
action class BookConfig(admin.ModelAdmin):
list_display
list_display_links
search_fields
list_filter
action
admin.site.register(Book,BookConfig) 2 知识点 url()的使用 情况1:url(r'^book/', views.book), # book(request) 情况2 分发:
url(r"^yuan/", ([
url(r'^test01/', ([
url(r'^test04/', test04),
url(r'^test05/', test05),
], None, None)),
url(r'^test02/', test02),
url(r'^test03/', test03),
], None, None)
) 单例模式
生成单例模式的方式:
(1)使用 __new__
(2)使用模块
class A()
pass
a=A() admin源码:
1 启动文件
class StarkConfig(AppConfig):
name = 'stark'
def ready(self):
autodiscover_modules('stark') 2 注册 admin.py admin.site.register(Book,BookConfig) 源码: class AdminSite():
def __init__(self, name='admin'):
self._registry = {} def register(self,model,admin_class):
if not admin_class:
admin_class = ModelAdmin self._registry[model] = admin_class(model, self) site=AdminSite() 3 设计url 如何通过model类变量获取该模型的字符串名称和该模型所在app的字符串名称:
print("===>", model._meta.model_name)
print("===>", model._meta.app_label) 在ModelStark中:
self.model: 用户当前访问的模型表 查看页面:
表头
表数据
search
action
分页
filter 增删改(modelForm) pop 作业1: 访问任何模型时都有编辑,删除,选择
作业2:
如果用户没有配置list_display,显示对象
作业3:
名称空间