姜戈教程"Write Views That Actually Do Something"



我一直在编写Django教程。我的部分是"写实际做某事的观点"。(第3部分)

我正在尝试使用它给你的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

Django视图函数或类使用您定义的模板,因此您不必在URL中指定它。urls.py文件与您定义的正则表达式相匹配,用于向视图发送请求。

如果确实想要使用该URL,则必须在urls.py中定义^polls/index.html$并将其引导到您的视图中。

根据您的要求,听起来您实际上想要在urls.pyurlpatterns中定义的URL上输出一个静态html文件。

我强烈建议您查看基于类的视图。https://docs.djangoproject.com/en/1.7/topics/class-based-views/#simple-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()),
)

最新更新