首页 > 解决方案 > Trying to reach url with Path include() shows 404 in Django

问题描述

first of I want to apologize if I use the wrong terms or words in my question. I'm completely new to Django and got only a few months of experience with python. I hope you can understand my question anyways. I also want to acknowledge the fact that I'm using some imports that are not needed here and might not be relevant to the latest version of Django, I'm starting to get lost in all the things I've tried from other threads to solve my problem.

I'm having some problems with showing a page from apps url. I'm getting redirected to my homepage when trying to reach localhost:8000/articles (because /articles gives 404 error) I'm not sure exactly what code I need to include here, so bear with me.

articles/urls.py and 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")

The project's urls.py and project's views.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")

Im getting no errors or such. So, my question is - does anybody have a clue why /articles generate 404 error?

Thank you in advance.

标签: pythondjango

解决方案


Firstly, don't use ^$ with path(). You only use regular expressions with re_path.

path('', views.article_list),

Usually, /articles will be redirected to /articles/ with a trailing slash.

However, in your case, you have a catch-all pattern:

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

This matches /articles, so you see the home page. Note it's not redirected as you say in your answer, the browser bar will still show /articles.

Unless you have a really good reason to have the catch all, I suggest you remove it and change it to

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

or

path('', views.homepage),

That way, you'll see the homepage for localhost:8000, localhost:8000/articles will be redirected to localhost:8000/articles/, and you'll get a 404 for pages that don't exist, e.g. localhost:8000/art/


推荐阅读