user5639245
user5639245

Reputation:

Python Django urls not working how they should?

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

import main.views
urlpatterns = [
    path('', main.views.index, name="index"),
    path('story/', main.views.story, name="story"),
    path('haxs/', main.views.haxs, name="haxs"),
    path('contact/', main.views.contact, name="contact"),
    path('admin/', admin.site.urls),
]

.

<li class="nav-item"><a class="nav-link" href="/">home</a></li>
<li class="nav-item"><a class="nav-link" href="story/">our story</a></li>
<li class="nav-item"><a class="nav-link" href="haxs/">haxs</a></li>
<li class="nav-item"><a class="nav-link" href="contact/">contact us</a></li>

I am working on a python django website and my urls are not working properly. I have included my urls.py and the nav links which are the same on each page. From home I can go to all the other pages and from the other pages I can go back to home.

My problem is when I go from for example: haxs to contact it does not work and the code url becomes "http://127.0.0.1:8000/haxs/story/" when it should just be "http://127.0.0.1:8000/story/" . It is like that with our story/haxs/contact, I can not go between them pages. How do I fix this?

Upvotes: 1

Views: 2873

Answers (3)

Novfensec
Novfensec

Reputation: 116

Just change hrefs to relate with the server like this:

<a href={℅ url 'name of urls defined' ℅}>pagename</a>

{℅ url 'urls' ℅} is the django url variable to define app urls!

Upvotes: 1

K.Pardo
K.Pardo

Reputation: 131

Adding to @neverwalkaloner answer, I would recommend adding a namespaces to your urls. It helps with legibility because you can identify exactly from which app you're calling that url from.

I'm going to assume your app name is main.

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

import main.views

    app_name = 'main' 
    urlpatterns = [
        path('', main.views.index, name="index"),
        path('story/', main.views.story, name="story"),
        path('haxs/', main.views.haxs, name="haxs"),
        path('contact/', main.views.contact, name="contact"),
        path('admin/', admin.site.urls),
    ]

    <li class="nav-item"><a class="nav-link" href="{% url 'main:story' %}">our story</a></li>

Hope this helps!

Upvotes: 2

neverwalkaloner
neverwalkaloner

Reputation: 47374

You can simply fix it by prepending url with /:

<li class="nav-item"><a class="nav-link" href="/story/">our story</a></li>

But better to use Django's named url feature:

<li class="nav-item"><a class="nav-link" href="{% url 'story' %}">our story</a></li>

Upvotes: 2

Related Questions