在Django视图中创建包含所有函数视图类的方法如下:
views.py
。django.shortcuts
和django.http
。from django.shortcuts import render
from django.http import HttpResponse
class MyView1:
def get(self, request):
# 处理GET请求的逻辑
return HttpResponse("This is the GET response")
def post(self, request):
# 处理POST请求的逻辑
return HttpResponse("This is the POST response")
class MyView2:
def get(self, request):
# 处理GET请求的逻辑
return HttpResponse("This is another GET response")
def post(self, request):
# 处理POST请求的逻辑
return HttpResponse("This is another POST response")
views.py
文件中创建一个包含所有函数视图类的字典。views_dict = {
'my_view1': MyView1(),
'my_view2': MyView2(),
}
def dynamic_view(request, view_name):
if request.method == 'GET':
return views_dict[view_name].get(request)
elif request.method == 'POST':
return views_dict[view_name].post(request)
else:
return HttpResponse("Method not allowed")
dynamic_view
函数与相应的URL路径进行关联。from django.urls import path
from . import views
urlpatterns = [
path('dynamic/<str:view_name>/', views.dynamic_view, name='dynamic_view'),
]
现在,你可以通过访问/dynamic/my_view1/
和/dynamic/my_view2/
来调用相应的函数视图类,并根据请求方法执行相应的逻辑。
领取专属 10元无门槛券
手把手带您无忧上云