2015-02-11 17 views
0

我一直在Django教程上工作。我正在寫的是「寫實際上做些事情的觀點」。 (第3部分)Django教程「寫視圖實際上做什麼」

我試圖用它給你的index.html的模板,但我不斷收到404錯誤,說

Request Method: GET 
Request URL: http://127.0.0.1:8000/polls/index.html 

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: 
^polls/ ^$ [name='index'] 
^polls/ ^(?P<question_id>\d+)/$ [name='detail'] 
^polls/ ^(?P<question_id>\d+)/results/$ [name='results'] 
^polls/ ^(?P<question_id>\d+)/vote/$ [name='vote'] 
^admin/ 
The current URL, polls/index.html, didn't match any of these. 

我不知道,如果正則表達式的一個錯了?我現在一直在搞這個,現在我沒有辦法讓它工作。

我可以去/民意調查很好。但/polls/index.html不起作用。

任何幫助,將不勝感激。

的Django的版本,我使用的是1.7.4

回答

4

Django的視圖函數或類使用您定義的模板,讓你不必在URL中指定。 urls.py文件與您定義的正則表達式匹配,以將請求發送到視圖。

如果真正想使用URL,你會在你的urls.py定義^polls/index.html$並將其引導到您的視圖。

+0

請問我在/mysite/polls/urls.py文件或/mysite/mysite/urls.py文件中添加該文件嗎? – DrZoo 2015-02-11 22:38:17

+0

如果您已經向'polls/urls.py'發送了與'polls'相匹配的任何內容,那麼您需要在'mysite/polls/urls.py'中定義'^ index.html $'' – 2015-02-11 22:41:27

+0

'mysite的問題'如果我還記得,在教程中,'mysite'是項目和應用程序。你可以在'mysite'目錄中設置'settings.py'和'wsgi.py',然後執行'python manage.py startapp myapp',你將會有'models.py'' views.py'和' urls.py'在那。將'myapp'添加到'INSTALLED_APPS',然後將你的'/ polls /'url加入'myapp' – 2015-02-11 22:46:17

0

從你的要求,它聽起來像你基本上想輸出一個靜態html文件在你的urlpatternsurls.py定義的URL。

我強烈建議你看看基於類的視圖。 https://docs.djangoproject.com/en/1.7/topics/class-based-views/#simple-usage-in-your-urlconf

從你所得到的最快的方式去渲染polls/index.html會是這樣的;

# some_app/urls.py 
from django.conf.urls import patterns 
from django.views.generic import TemplateView 

urlpatterns = patterns('', 
    (r'^polls/index.html', TemplateView.as_view(template_name="index.html")), 
) 

但我相信你會想把事情傳遞給模板,所以基於類的視圖將成爲你所需要的。因此,上面加入上下文的替代方案是;

# some_app/views.py 
from django.views.generic import TemplateView 

class Index(TemplateView): 
    template_name = "index.html" 

    def get_context_data(self, **kwargs): 
     context = super(Index, self).get_context_data(**kwargs) 
     context['foo'] = 'bar' 
     return context 

那麼顯然將{{ foo }}index.html將輸出欄給用戶。你會更新你的urls.py;

# some_app/urls.py 
from django.conf.urls import patterns 
from .views import Index 

urlpatterns = patterns(
    '', 
    (r'^polls/index.html', Index.as_view()), 
) 
相關問題