要调用基于类的视图方法而不经过urls.py,可以使用Django的内置的URL调度器,即django.core.urlresolvers.resolve()
函数。以下是一个示例代码:
from django.core.urlresolvers import resolve
from django.http import HttpRequest
def call_view():
# 创建一个HttpRequest对象,模拟请求
request = HttpRequest()
request.method = 'POST'
request.POST['param1'] = 'value1'
request.POST['param2'] = 'value2'
# 解析URL并获取视图函数
view_func = resolve('/your_view_url/').func
# 调用视图函数,并传入HttpRequest对象作为参数
response = view_func(request)
return response
在上面的示例中,我们创建了一个HttpRequest
对象并设置请求方法为POST,并添加了一些POST参数。然后使用resolve()
函数解析指定的URL路径,获取到对应的视图函数。最后,调用视图函数,并将HttpRequest
对象作为参数传入,即可实现调用基于类的视图的POST方法。