Python 使用 mysite.urls 中定义的 URLconf,Django 按以下顺序尝试了这些 URL 模式:

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41605073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:18:30  来源:igfitidea点击:

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

pythondjangourl

提问by HLH

I know this question has been asked before, but I haven't found an answer that solves my situation.

我知道以前有人问过这个问题,但我还没有找到解决我情况的答案。

I'm looking at the Django tutorial, and I've set up the first URLs exactly as the tutorial has it, word for word, but when I go to http://http://localhost:8000/polls/, it gives me this error:

我正在查看 Django教程,并且我已经按照教程中的内容逐字设置了第一个 URL,但是当我转到http://http://localhost:8000/polls/ 时,它给我这个错误:

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/ ^% [name='index']
^admin/
The current URL, polls/, didn't match any of these.

I'm using Django 1.10.5 and Python 2.7.

我正在使用 Django 1.10.5 和 Python 2.7。

Here is the code I have in relevant url and view files:

这是我在相关 url 和视图文件中的代码:

In mysite/polls/views.py:

在 mysite/polls/views.py 中:

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
  return HttpResponse("Hello, world. You're at the polls index.")

In mysite/polls/urls.py:

在 mysite/polls/urls.py 中:

from django.conf.urls import url

from . import views

urlpatterns = [
  url(r'^%', views.index, name='index'),
]

In mysite/mysite/urls.py:

在 mysite/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),
]

What's going on? Why am I getting 404s?

这是怎么回事?为什么我会收到 404?

采纳答案by v1k45

Your url conf regex is incorrect, you have to use $instead of %.

您的网址的conf正则表达式是不正确,你必须使用$替代%

from django.conf.urls import url

from . import views

urlpatterns = [
   url(r'^$', views.index, name='index'),
]

The $acts as a regex flag to define the end of the regular expression.

$作为一个正则表达式标志来定义正则表达式的结尾。