Website creates a new non-existent webpage after I visit website/class_id

Question:

My website creates a new non-existent website, after I visit my website/näytä_luokka/# (also, class_id). If I try to go to a page that is in the same urls.py file, I get an error because it tries to find a page website/näytä_luokka/luokat instead of going to website/luokat. This happens through navbar. If I try to go to a link that is in another urls.py, everything works fine. Switching from /luokat to other pages works also fine.

I am using django to create website.

So, here’s a couple examples from my

urls.py

from django.urls import path
from . import views

urlpatterns = [

path('näytä_luokka/<luokka_id>', views.näytä_luokka, name="näytä-luokka"),

path('luokat', views.kaikki_luokat, name="luokat"),
]

and .views

def näytä_luokka(request, luokka_id):
    luokkalistaus = luokka.objects.get(pk=luokka_id)
    return render(request, 'tietokanta/näytä_luokat.html', 
        {'luokkalistaus': luokkalistaus})
def kaikki_luokat(request):
    luokkalista = luokka.objects.all().order_by('nimi')
    return render(request, 'tietokanta/luokat.html', 
        {'luokkalista': luokkalista})

the navbar

     
            </li>
      <li class="nav-item">
        <a class="nav-link" href="luokat">Luokat</a>
      </li>

I tried adding / after id number, but id didn’t do anything.

Asked By: Charoi

||

Answers:

The path in your urls.py
path('näytä_luokka/<luokka_id>', views.näytä_luokka, name="näytä-luokka"),

Specifically, the <luokka_id> is what is creating a webpage for you. That is what is supposed to happen in a path like that. It’s the beauty of what Django can do; create urls dynamically, in this case a page that follows a template, but is unique to luokka_id.

The error you get when you try website/näytä_luokka/luokat happens because your view def näytä_luokka(request, luokka_id): is looking for what I guess is a number (an int) for the luokka_id but instead you are feeding it the string ‘luokat’ because that is the part of the url after website/näytä_luokka/.

Now, in your template you are referencing the href incorrectly. It should be:

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

I would need to see more of your code, and maybe a better sense of what you want your page to do in order to help further, but I hope this helps.

Answered By: raphael

There are two mistakes.

  1. By default <luokka_id> url param is considered as str type i.e. <str:luokka_id> and <luokka_id> is same. So it should be <int:luokka_id>.

urls.py:

urlpatterns = [
    path('näytä_luokka/<int:luokka_id>/', views.näytä_luokka, name="näytä-luokka"),
    path('luokat/', views.kaikki_luokat, name="luokat"),
]
  1. You should url tags correctly, so in template it should be:
<li class="nav-item">
    <a class="nav-link" href="{% url 'luokat' %}">Luokat</a>
</li>

Note: Always give / at the end of every route.

Answered By: Sunderam Dubey