如何实现批量设计url?
1、创建Django项目
2、新建app01 和 app02
3、在models.py中创建模型
4、在settings.py中完成数据库配置、app配置等
5、数据库迁移
6、在urls.py中配置路径:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.shortcuts import HttpResponse
from app01 import views def get_method():
"""增删改查操作"""
method_list = []
method_list.append(url(r'^add/', views.add))
method_list.append(url(r'^(\d+)/delete/', views.delete))
method_list.append(url(r'^(\d+)/edit/', views.edit))
method_list.append(url(r'^$', views.show))
return method_list def get_urls():
"""匹配路径"""
models = admin.site._registry # 获取所有模型表
url_list = []
for model in models:
app_label = model._meta.app_label # app名称
model_name = model._meta.model_name # 模型表名称
print("app_label:", app_label, "--", "model_name:", model_name)
url_list.append(url(r'%s/%s/' % (app_label, model_name), (get_method(), None, None)))
return url_list urlpatterns = [
# url设计
url(r'^yuan/', (get_urls(), None, None))
]
7、在views.py中编写视图函数:
def add(request):
return HttpResponse("add") def delete(request, delete_id):
return HttpResponse("delete") def edit(request, edit_id):
return HttpResponse("edit") def show(request):
return HttpResponse("show")
这样通过http://127.0.0.1:8080/yuan/app01/book/2/delete/或者http://127.0.0.1:8080/yuan/app01/book/add/等路径,便可以访问相应的视图函数