給定一個像/home/
這樣的URI我想查找與此相對應的查看功能,最好是以app.views.home
或<app_label>.<view_func>
的形式。有沒有一個函數可以給我這個?從請求uri獲取查看功能?
12
A
回答
23
您可以使用由django提供的resolve方法來獲取該函數。您可以使用返回的函數的__module__
屬性來獲取應用程序標籤。這將返回一個字符串,如project.app.views
。因此,像這樣:
from django.core.urlresolvers import resolve
myfunc, myargs, mykwargs = resolve("/hello_world/")
mymodule = myfunc.__module__
0
基於KillianDS's answer,這裏是我的解決方案:
from django.core.urlresolvers import resolve
def response(request, template=None, vars={}):
if template is None:
view_func = resolve(request.META['REQUEST_URI'])[0]
app_label = view_func.__module__.rsplit('.', 1)[1]
view_name = view_func.__name__
template = '%s.html' % os.path.join(app_label, view_name)
return render_to_response(template, vars, context_instance=RequestContext(request))
現在你可以叫return response(request)
在您的視圖funcs中結束,它會自動加載app/view.html
作爲模板並傳入請求上下文。
3
由於Django 1.3(2011年3月)模塊中的resolve
函數返回ResolverMatch
對象。其中提供對已解析的URL匹配的所有屬性的訪問,包括視圖可調用路徑。
>>> from django.core.urlresolvers import resolve
>>> match = resolve('/')
>>> match.func
<function apps.core.views.HomeView>
>>> match._func_path
'apps.core.views.HomeView'
鑑於您已經有了請求,您可以簡單地執行「request.resolver_match」而不是調用resolve – 2016-05-27 06:52:35