投票应用程序- Django教程无法工作

3
我正在学习 Django 的 投票教程。我已经完成了第六部分的开头。
不知何故,我的所有基于类的通用视图都能正常工作,除了基于类的索引视图。当尝试加载 localhost:8000/ 时,我会得到以下错误:
Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^admin/

The current URL, , didn't match any of these.

这是我的 mysite/urls.py 文件:

from django.conf.urls import include, url
from django.contrib import admin


urlpatterns = [
   url(r'^polls/', include('polls.urls')),
   url(r'^admin/', admin.site.urls),
]

这是我的 polls/urls.py 文件

from django.conf.urls import url

from . import views

app_name = 'polls'

urlpatterns = [
   url(r'^$', views.IndexView.as_view(), name='index'),
   url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
   url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
   url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

这里是投票/views.py文件。我只贴出了IndexView部分,其余的基于类的视图目前都在工作中:

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from django.utils import timezone

from .models import Choice, Question

# Create your views here.
class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        # Return last five published questions (not inc. future)
        return Question.objects.filter(
        pub_date__lte=timezone.now()
        ).order_by('-pub_date')[:5]

我有什么遗漏吗?任何帮助都将不胜感激。

1个回答

5

您的索引URL模式位于 polls / urls.py 中,您在其中包含了 r'^polls/' ,因此您应该访问它:

http://localhost:8000/polls/

访问 http://localhost:8000/ 出现 404 错误是正常的行为,因为您的主 urls.py 只包含 admin/polls/ 的 url。您需要在 main/urls.py 中添加一个正则表达式为 r'^$' 的 url 模式来避免 404 错误。


谢谢!作为额外的奖励,您的答案教会了我如何思考“索引”与我的网站和投票应用程序内部的关系。非常感谢。 - Dan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接