民意调查申请 - django教程无效

时间:2017-02-04 21:11:50

标签: python django

我正在研究Polls tutorial for Django。我已经做到了第六部分的开头。

出于某种原因,我所有基于类的通用视图都在使用 EXCEPT 基于类的索引视图。当尝试加载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),
]

这是我的民意调查/ 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 个答案:

答案 0 :(得分:4)

您的索引网址格式位于polls/urls.pyr'^polls/'中包含该格式,因此您应该访问以下网址:

http://localhost:8000/polls/

http://localhost:8000/获取404是预期的行为,因为您的主urls.py仅包含admin/polls/的网址。您必须将正则表达式r'^$'的网址格式添加到main/urls.py才能停止404。