stark - 3 ⇲自动生成URL及视图

以往建立了一张表,需要

1.为每张表创建4个url

2.为每张表创建4个视图函数

 urlpatterns = [
url('^role/list/$',role.role_list,name='role_list'),
url('^role/add/$',role.role_add,name='role_add'),
url('^role/edit/(?P<pk>\d+)/$',role.role_edit,name='role_edit'),
url('^role/del/(?P<pk>\d+)/$',role.role_del,name='role_del'),
] 如果我们需要对大量的表进行这些操作,虽简单但是耗费时间和精力,且不保证细节会百分百正确。再有的是 程序狗为写重复的代码可耻!

现在:为app中的每个model类自动创建URL以及相关视图函数

 def url(regex, view, kwargs=None, name=None):
return re_path(regex, view, kwargs, name)

url函数 源码

返回值主要参数为regex ,view

前面的StarkSite类中,同样是regex , view

if prev:
patterns.append(url(r'^%s/%s/%s/'%(app_name,model_name,prev),(handler.get_urls(),None,None)))
else:
patterns.append(url(r'^%s/%s/' % (app_name, model_name), (handler.get_urls(), None,None)))

prev前缀。(默认prev=None)使用者可以通过导入参数prev,实现正则不同前缀的url。

在StarkHandler类中get_urls生成相关视图函数:

 def get_urls(self):
"""
生成视图函数
:return:
"""
patterns = [
url(r'^list/$', self.wapper(self.list_view), name=self.get_list_url_name),
url(r'^add/$', self.wapper(self.add_view), name=self.get_add_url_name),
url(r'^change/(?P<pk>\d+)/$', self.wapper(self.change_view), name=self.get_change_url_name),
url(r'^delete/(?P<pk>\d+)/$', self.wapper(self.delete_view), name=self.get_delete_url_name),
] patterns.extend(self.extra_urls())
return patterns

其中,各视图函数:

 def list_view(self,request,*args,**kwargs):

     ###################### 处理action #####################

     action_list = self.action_list
action_dict = {func.__name__:func.text for func in action_list} if request.method == 'POST':
func_name = request.POST.get('action')
if func_name and func_name in action_dict: #逻辑优化,防止被 方法乱入
func = getattr(self,func_name)
func(request) ###################### 1.搜索(有值才会显示搜索框) #####################
search_list = self.get_search_list()
search_value = request.GET.get('q','') from django.db.models import Q
conn = Q()
conn.connector = 'OR' if search_value:
#Q,用于构造复杂的ORM查询条件
for item in search_list:
conn.children.append((item,search_value)) ######################### 2.获取排序 ###############################
order_list = self.get_order_list() #组合搜索条件字典
search_dict = self.get_search_group_condition(request) #自定义方法筛选后的结果
queryset = self.get_queryset(**kwargs)
# print(queryset)
queryset = queryset.filter(conn).filter(**search_dict).all().order_by(*order_list) ###################### 3.处理分页(使用组件) #######################
all_count = queryset.count()
query_params = request.GET.copy() # ?=page=1&name='李四'
query_params._mutable = True #query_params['page']默认是不可以修改的 pager = Pagination(
current_page=request.GET.get('page'),
all_count=all_count,
base_url=request.path_info,
query_params=query_params,
per_page=self.per_page_count,
) ###################### 4.处理表格 ##############################
list_display = self.get_list_display()
# 4.1处理表头
header_list = []
if list_display:
for multi_key in list_display:
if isinstance(multi_key,FunctionType): #判断 传入值是否为函数
verbose_name = multi_key(self,obj=None,is_header=True)
else:
verbose_name = self.model_class._meta.get_field(multi_key).verbose_name
header_list.append(verbose_name)
else:
header_list.append(self.model_class._meta.model_name) # 4.2处理表的内容
data_list = queryset[pager.start:pager.end] body_list = []
for row in data_list: #row 是UserInfo object (1)
row_list = [] if list_display:
for multi_key in list_display:
if isinstance(multi_key,FunctionType):
row_list.append(multi_key(self,row,is_header=False,*args,**kwargs))
else:
row_list.append(getattr(row,multi_key)) #获取UserInfo object (1)的属性
else:
row_list.append(row) body_list.append(row_list) ###################### 5.处理添加按钮 ##############################
add_btn = self.get_add_btn(**kwargs) #是一个URL ###################### 6.处理组合搜索 ##############################
search_group_row_list = []
search_group = self.get_search_group() # ['gender', 'depart']
for keyword_object in search_group: #keyword是一个Option类实例对象
row = keyword_object.get_queryset_or_tuple(self.model_class,request,*args,**kwargs)
#返回的是一个SearchGroupRow对象,且可迭代
search_group_row_list.append(row) return render(request,
self.list_template or 'list.html',
{'body_list':body_list,
'header_list':header_list,
'pager':pager,
'add_btn':add_btn,
'search_list':search_list,
'search_value':search_value,
'action_dict':action_dict,
'search_group_row_list':search_group_row_list})

list_view

 def add_view(self,request,*args,**kwargs):
"""
添加视图
:param request:
:return:
""" model_form = self.get_model_form()
if request.method == 'GET':
form = model_form
return render(request, 'change.html', {'form': form}) form = model_form(data=request.POST)
if form.is_valid():
response = self.save(request,form,False,*args,**kwargs)
return response or redirect(self.reverse_list_url(**kwargs))
return render(request,'change.html',{'form':form})

add_view

 def change_view(self,request,pk,*args,**kwargs):
"""
编辑视图
:param request:
:param pk:
:return:
"""
checked_obj = self.get_change_object(request, pk, *args, **kwargs) if not checked_obj:
return render(request,'rbac\error.html') model_form = self.get_model_form()
if request.method == 'GET':
form = model_form(instance=checked_obj)
return render(request, 'change.html', {'form': form}) form = model_form(data=request.POST,instance=checked_obj)
if form.is_valid():
response = self.save(request, form, True, *args, **kwargs)
return response or redirect(self.reverse_list_url(**kwargs))
return render(request, 'change.html', {'form': form})

change_view

 def delete_view(self,request,pk,*args,**kwargs):
"""
删除视图
:param request:
:param pk:
:return:
"""
checked_obj = self.model_class.objects.filter(pk=pk).first()
if not checked_obj:
return render(request,'rbac\error.html',) list_url = self.reverse_list_url(**kwargs)
if request.method == 'GET':
return render(request,'delete.html',{'list_url':list_url}) response = self.delete_object(request, pk, *args, **kwargs)
return response or redirect(list_url)

delete_view

以及生成各URL的别名:

 def extra_urls(self):
return [] def get_url_name(self,param):
"""
返回别名(所有别名最后在这里处理)
:param param:
:return:
"""
app_name = self.model_class._meta.app_label
model_name = self.model_class._meta.model_name
if self.prev:
return '%s_%s_%s_%s' %(app_name,model_name,self.prev,param) #Web_customer_public_list
return '%s_%s_%s' %(app_name,model_name,param) @property
def get_list_url_name(self):
"""
获取列表页面URL的name
:return:
"""
return self.get_url_name('list') @property
def get_add_url_name(self):
"""
获取列表页面URL的name
:return:
"""
return self.get_url_name('add') @property
def get_change_url_name(self):
"""
获取列表页面URL的name
:return:
"""
return self.get_url_name('change') @property
def get_delete_url_name(self):
"""
获取列表页面URL的name
:return:
"""
return self.get_url_name('delete')
上一篇:C# oleDb方法读取Excel文件


下一篇:WebForms UnobtrusiveValidationMode 需要“jquery”ScriptResourceMapping。请添加一个名为 jquery (区分大小写)的 ScriptResourceMapping。