【发布时间】:2021-03-13 15:57:21
【问题描述】:
我自己开始学习 Django,在理解 URL 和路径如何工作方面存在问题。
错误信息是:
找不到页面 (404)
请求方法:GET
请求网址:http://127.0.0.1:8000/question/1/
使用 not_bad.urls 中定义的 URLconf,Django 按以下顺序尝试了这些 URL 模式:
[名称='索引']
[名称='详细信息']
[名称='结果']
[名称='投票']
微三亚/
当前路径 question/1/ 与其中任何一个都不匹配。
在项目文件中我有这个代码:
not_bad\urls.py:
from django.contrib import admin
from django.urls import include
from django.urls import path
urlpatterns = [
path('', include('polls.urls')),
path('microsanya/', admin.site.urls),
]
投票/urls.py:
from django.urls import include, path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'),
path('', views.detail, name='detail'),
path('', views.results, name='results'),
path('', views.vote, name='vote' ),
]
polls/views.py
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from django.shortcuts import redirect
from django.shortcuts import render
from django.http import Http404
from . models import Question, Choice
def index(request):
question = Question.objects.all()
return render(request, "index.html", {"latest_questions": Question.objects.order_by('-pub_date')[:5]})
def detail(request, question_id):
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404
return render(request, 'polls/answer.html', {'question': question})
def answer(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
question = question.question_set.get(pk=request.POST['question'])
except (KeyError, Question.DoesNotExist):
return render(request, 'answer.html', {'question': question, 'error_message': 'Question does not exist'})
else:
if question.correct:
return render(request, "index.html", {"latest_questions": Question.objects.order_by('-pub_date')[:5], "message": "Nice! Choose another one!"})
else:
return render(request, 'answer.html', {'question': question, 'error_message': 'Wrong Answer!'})
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
我有名为 index.html 和 answer.html 的文件,但我认为问题不在于它们。
【问题讨论】:
-
您必须像这样更改 url 模式:
path('question/<int:question_id>/', views.detail, name='detail'),等。查看 django 文档以获取更多示例:docs.djangoproject.com/en/3.1/topics/http/urls/#example -
目前 PATTERNS 未在您的 urlpatterns 配置中定义,因此请定义它们。每个 url 模式 的不同模式/模板/正则表达式。
question/<int:id>用于问题详情页面,vote/<int:id>或question/int:id/vote用于投票等。 -
非常感谢您的帮助,我终于弄清楚了它是如何工作的:)
标签: python django django-urls