我正在创建一个 Django 应用程序,但遇到了无法识别路由的问题。这是我正在尝试创建的同一个 DJango 投票应用程序,但文档代码不起作用。下面是我的代码:
djangoproject/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^simpleapp/', include('simpleapp.urls')),
url(r'^admin/', admin.site.urls),
]
simpleapp/views.py
from django.shortcuts import render
from django.http import HttpResponse, request
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
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)
simpleapp/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# ex: /simpleapp/
# url('', views.index, name='index'),
# ex: /simpleapp/5/
url('<int:question_id>/', views.detail, name='detail'),
# ex: /simpleapp/5/results/
url('<int:question_id>/results/', views.results, name='results'),
# ex: /simpleapp/5/vote/
url('<int:question_id>/vote/', views.vote, name='vote'),
]
如果我取消注释 simpleapp/urls.py
代码的 '' path 的第一个 url,显示的所有页面都是 '' path。但是,如果我保留 url '' 路径的注释,那么路由会给我以下错误:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/simpleapp/34/
Using the URLconf defined in simple_django.urls, Django tried these URL patterns, in this order:
^simpleapp/ <int:question_id>/ [name='detail']
^simpleapp/ <int:question_id>/results/ [name='results']
^simpleapp/ <int:question_id>/vote/ [name='vote']
^admin/
The current path, simpleapp/34/, 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.
我无法使用 django.conf.urls
或 django.urls
导入 path()
。 url()
成功。我正在使用 python 版本 3.6.7 和 Django 版本 2.1.5。我错过了什么?
最佳答案
您在 simpleapp/urls.py 中使用的是路径语法,而不是正则表达式。将其更改为:
urlpatterns = [
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
您的项目 URL 使用正则表达式,因此您不应更改它们,尽管您可能希望它们保持一致。
关于python - 无法让 Django 声明的应用程序路由作为页面工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54305001/