2013-06-04 20 views
0

我想使用基於類的視圖發送一個變量。以下是url文件的代碼如何在我的觀點中獲得價值?我試圖使用基於類的視圖

from django.conf.urls import patterns, include, url 
from myapp.views import foo 

urlpatterns = patterns('', 
    (r'^/$', foo.as_views(template = 'home.html')), 
    (r'^about/$', foo.as_views(template = 'about.html')), 
) 

如何在我的視圖文件中的foo類中訪問這個?我試圖做這樣的事情:

return render(request, template_n) 

回答

1

傳遞給as_view的參數指定爲實例變量上的基於類的視圖,以便您可以可以self.template,即:

... 
return render(request, self.template, {...}) 

一點題外話,如果你使用的是拍攝的蛞蝓,例如一個名爲URL模式:

url(r'^about/(?P<slug>[\w-]+)/$', foo.as_views(template='about.html')), 

你將有機會獲得slug變量這是通過使用kwargs實例變量通過url傳遞:

self.kwargs['slug'] 
+0

對不起,我知道這應該很容易。但我不知道爲什麼我無法弄清楚。 這就是我試圖做 - 類Foo(): \t高清template_loader(請求): \t \t返回渲染(請求,模板= self.template) –

+0

只是做:'渲染(請求,self.template )' –

相關問題