我正在遵循Django教程,该教程当前位于第6部分。

当我从网页上单击列表时出现错误。我抬头查找问题发生的位置,但找不到。

这是来自网络浏览器的消息:

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/polls/1//
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

polls/ [name='index']
polls/ <int:pk>/ [name='detail']
polls/ <int:pk>/results/ [name='results']
polls/ <int:question_id>/vote/ [name='vote']
admin/
The current path, polls/1//, didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.


追溯
“ GET / polls / 1 // HTTP / 1.1” 404 2703

mysite / polls / views.py

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

from .models import Choice, Question

# ...
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 (not including those set to be
        published in the future).
        """
        return Question.objects.filter(
            pub_date__lte=timezone.now()
        ).order_by('-pub_date')[:5]

class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'
    def get_queryset(self):
        """
        Excludes any questions that aren't published yet.
        """
        return Question.objects.filter(pub_date__lte=timezone.now())

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

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            '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=(question.id,)))


mysite / polls / urls.py

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]


mysite / urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]


mysite / polls / templates / polls / index.html

{% load static %}

<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="{% url 'polls:detail' question.id %}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}


mysite / polls / templates / polls / detail.html

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>


mysite / polls / templates / polls / result.html

<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>

最佳答案

网址末尾有两个斜杠('//'),该斜杠应该只是一个:

http://localhost:8000/polls/1/

更具体地说,在polls / index.html模板中,您具有以下行:

<li><a href="{% url 'polls:detail' question.id %}/">{{ question.question_text }}</a></li>


在这一行中,此部分为您生成网址:

{% url 'polls:detail' question.id %}


变成:

http://localhost:8000/polls/1/


但是您在其后添加了一个额外的斜杠,请看下面的字符串的结尾:

"{% url 'polls:detail' question.id %}/"


删除它,我认为您的代码应该可以工作。

关于python - 为什么我在Django中出现此错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50791827/

10-12 21:57