Every url in a django app only renders home.html

Viewed 108

So, I am not really lucky with latest django version tutorials, so I've had some problems with things that changed between some versions. One of this things is: althought I do exactly as I read/watch in the tutorials I always get the same result - all urls redirect to the same HTML page.

Here is my root urls.py

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('theblog.urls')),
]

Here is my app urls:

from django.conf.urls import url, include
from .views import HomeView, ArticleDetailView

urlpatterns = [
    url('', HomeView.as_view(), name='home'),
    url('^article/<int:pk>', ArticleDetailView.as_view(), name='article-detail'),
]

For example, when I go to localhost:8000/articles/1 (or any other pk), it renders home.html (HomeView class) as if it was localhost:8000/.

Hope you can help me. Thanks!

2 Answers

It may be due to this line

url('', HomeView.as_view(), name='home'),

Because url wraps re_path there may be some logic which will treat the blank regex string as a wildcard. Try changing it to '/'

url('/', HomeView.as_view(), name='home'),

There are two things wrong with your code.

url('^article/<int:pk>', ArticleDetailView.as_view(), name='article-detail'),

This will not work. If you want to use url. you can't use <int:pk>, you need to use a RegEx:

url("article/([0-9]+)/", ArticleDetailView.as_view(), name="article-detail")

Note that this will be deprecated in the future and if you are using django >=2.0 you should use path:

path("article/<int:article>/", ArticleDetailView.as_view(), name="article-detail")

However this will still direct you to the wrong view. django stops after the first URL pattern match.

Switch them around to fix that:

urlpatterns = [
    url("article/([0-9]+)/", ArticleDetailView.as_view(), name="article-detail"),
    # path("article/<int:article>/", ArticleDetailView.as_view(), name="article-detail"),  # alternative with path instead of url
    url('', HomeView.as_view(), name='home')
]
Related