【问题标题】:Polls application — django tutorial not working投票应用程序 — django 教程不工作
【发布时间】:2017-02-04 21:11:50
【问题描述】:

我正在处理Polls tutorial for 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),
]

这是我的投票/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'),
]

这里是 polls/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]

我错过了什么吗?任何帮助将不胜感激。

【问题讨论】:

    标签: python django


    【解决方案1】:

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

    http://localhost:8000/polls/
    

    http://localhost:8000/ 获取 404 是预期行为,因为您的主要 urls.py 仅包含位于 admin/polls/ 的网址。您必须使用正则表达式 r'^$'main/urls.py 添加一个 url 模式来停止 404。

    【讨论】:

    • 谢谢!作为额外的奖励,您的回答教会了我如何考虑与 mysite 与民意调查应用程序内部相关的“索引”。非常感谢。
    猜你喜欢
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    相关资源
    最近更新 更多