试图通过Path include()访问url在Django中显示404

2024-05-06 17:28:47 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,如果我在问题中使用了错误的术语或词语,我想道歉。我对Django是一个全新的人,只有几个月的python经验。我希望你无论如何都能理解我的问题。我还想承认一个事实,我正在使用一些这里不需要的导入,可能与最新版本的Django无关,我开始迷失在我从其他线程尝试解决问题的所有事情中

我在显示应用程序url中的页面时遇到一些问题。 当我试图访问localhost:8000/articles时,我被重定向到我的主页(因为/articles给出404错误) 我不确定这里需要包含什么代码,所以请耐心等待

articles/url.py和articles/views.py

from django.conf.urls import url
from django.urls import include, path
from django.conf.urls import include, url
from django.urls import path
from .import views


urlpatterns = [
    path('^$', views.article_list),

    ]



from django.shortcuts import render
    from django.http import HttpResponse
    
    # views
    def article_list(request):
        return render(request, "articles/article_list.html")

项目的URL.py和项目的视图.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from django.urls import include, path
from django.conf.urls import include, url
from django.urls import path, re_path
from .import views



urlpatterns = [
    path('admin/', admin.site.urls),
    path('articles/', include('articles.urls')),
    path('about/', views.about),
    re_path('^.*$', views.homepage)
]



from django.http import HttpResponse
from django.shortcuts import render
#Views
def homepage(request):
    # return HttpResponse('homepage')
    return render(request, "homepage.html")

def about(request):
    # return HttpResponse('about')
    return render(request, "about.html")

我没有收到任何错误之类的。 所以,我的问题是——有人知道为什么/articles会产生404错误吗

先谢谢你


Tags: pathdjangofrompyimporturlreturninclude
2条回答

首先,不要将^$path()一起使用。您只能将正则表达式与re_path一起使用

path('', views.article_list),

Usually/articles将被重定向到带有尾随斜杠的/articles/

但是,在您的情况下,您有一个包罗万象的模式:

re_path('^.*$', views.homepage)

这与/articles匹配,因此您可以看到主页。请注意,它并不像您在回答中所说的那样重定向到,浏览器栏仍将显示/articles

除非你有一个很好的理由拥有这个包罗万象的东西,否则我建议你把它去掉,改成

re_path('^$', views.homepage),

path('', views.homepage),

这样,您将看到localhost:8000的主页,localhost:8000/articles将被重定向到localhost:8000/articles/,对于不存在的页面,您将得到404,例如localhost:8000/art/

仅使用空字符串''而不是'^$

urlpatterns = [
  path('', views.article_list),
]

看看这里的最后一个例子:https://docs.djangoproject.com/en/3.1/topics/http/urls/#url-namespaces-and-included-urlconfs

*我不知道您使用的是什么django版本,但是对于正则表达式路径,您应该使用re_path()https://docs.djangoproject.com/en/3.1/ref/urls/#django.urls.re_path

相关问题 更多 >