【问题标题】:Django: Page not found (404)Django:找不到页面(404)
【发布时间】:2015-10-22 06:49:17
【问题描述】:

所以我正在阅读 Django 教程,使用版本 1.8

当我转到应该显示索引的页面时,它位于

http://127.0.0.1:8000/

我收到一个 404 错误提示

Page not found (404)
  Request Method:   GET
    Request URL:    http://127.0.0.1:8000/

Using the URLconf defined in forumtest.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
The current URL, , didn't match any of these.

这些是我的网址页面。

论坛测试/urls.py:

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


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

我也在用它自己的 urls.py 创建一个名为 polls 的应用

投票/urls.py:

from django.conf.urls import url

from . import views

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

这是我的浏览页面:

民意调查/views.py:

from django.shortcuts import render,get_object_or_404
from django.http import HttpResponseRedirect,HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic

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 the last five published questions"""
        return Question.objects.order_by('-pub_date')[:5]

class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'

class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'

def vote(request,question_id):
    p = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except(KeyError,Choice.DoesNotExist):
        #redisplay the question voting form
        return render(request,'polls/detail.html',{
            'question':p,
            'error_message': "you didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

我不知道如何解决这样的问题,所以如果有人能提供帮助,那就太好了。

谢谢。

【问题讨论】:

    标签: python django views django-urls


    【解决方案1】:

    错误消息告诉您出了什么问题。你已经在 /polls/ 下定义了 url,所以这是你应该去的地址。

    【讨论】:

    猜你喜欢
    • 2016-08-01
    • 2016-08-01
    • 2014-03-20
    • 2020-10-27
    • 2019-07-21
    • 1970-01-01
    • 2016-03-31
    • 2017-02-09
    • 2021-10-17
    相关资源
    最近更新 更多