Home > Back-end >  Django href link not routing to correct url
Django href link not routing to correct url

Time:10-27

The links within my pages/templates/base.html which are used for a header template results in 404 error. The pages load correctly when manually written 'http://127.0.0.1:8000' 'http://127.0.0.1:8000/about/'. I am using class based views and following chapter 3 of Django for beginners (William Vincent).

pages/templates/base.html:

<header>
    <a href="{% url 'home' %">Home</a> |
    <a href="{% url 'about' %">About</a>
</header>

pages/urls.py:

from django.urls import path
from .views import HomePageView, AboutPageView

urlpatterns = [
    path("", HomePageView.as_view(), name="home"),
    path("about/", AboutPageView.as_view(), name="about"),

]

portfolio/urls.py:

from django.contrib import admin
from django.urls import path, include


urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include("pages.urls")),
]

settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'pages.apps.PagesConfig',
]

pages/views.py:

from django.views.generic import TemplateView

# Create your views here.

    from django.http import HttpResponse
    
    class HomePageView(TemplateView):
        template_name = 'home.html'
    
    class AboutPageView(TemplateView):
        template_name = "about.html"

The error is as follows:

Using the URLconf defined in portfolio.urls, Django tried these URL patterns, in this order:
admin/
[name='home']
about/ [name='about']
The current path, about/{% url 'about' %, didn’t match any of these.

Terminal error:

Not Found: /{% url 'about' %
[26/Oct/2022 11:40:02] "GET /{% url 'about' % HTTP/1.1" 404 2497

I think the issue lies in pages/urls.py, as if click the 'home' link from 'http://127.0.0.1:8000/about/' the url is 'http://127.0.0.1:8000/about/{% url 'home' %'. I've tried to remove the "about/" from " path("about/", AboutPageView.as_view(), name="about"), "

I am also not sure whether the href tags have been written correctly. I have looked at this and this but can't figure it out. Thanks.

CodePudding user response:

{% url 'about' % <- you need to close it properly.

  • Related