Home > Enterprise >  How to go from one page to another in django?
How to go from one page to another in django?

Time:03-31

I am new in python programming and I created a project for learning. I have created three html pages when I click on the other page link it's show error page not found because url show previous page link with current page link (I don't know how to explain my problem)

For Example

I have two page index, home

if I am on index page(url for index page is "http://127.0.0.1:8000/index/") and want to go to the home page when I click on home page link its show an error because the url for home page is "http://127.0.0.1:8000/index/home/" and I want home page url like this "http://127.0.0.1:8000/home/". Same thing happen when I want to go from home page to index page but when I write manually, page open correctly

My code

reference code for index.html and home.html links

<a  href="home">Home Page</a>
<a  href="index">Index Page</a>

view.py

from django.shortcuts import render
from django.http import HttpResponse

def index_view(request):
    return render(request, "index.html")

def home_view(request):
    return render(request, "home.html")

app/urls.py

from django.urls import path

from . import views

urlpatterns= [
    path('index/', views.index_view),
    path('home/', views.home_view),

project/urls.py

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

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

CodePudding user response:

You need to make changes in 'app/urls.py' and 'href' attributes. In django, every URL should be accessed with name.

enter image description here

CodePudding user response:

From django-doc, you can use url tag of django, for using url tags you have to give name in the path function in urls.py file.

Try this:

app/urls.py

from django.urls import path

from . import views

urlpatterns= [
    path('index/', views.index_view,name='index'),
    path('home/', views.home_view,name='home')
]

In your template file you can use in following way:

<a  href="{% url 'home' %}">Home Page</a>
<a  href="{% url 'index' %}">Index Page</a>

Note: function based views like you have defined index_view and home_view, doesn't require view suffix. Only class based views require view suffix. So, it will be better if you use index and home.

  • Related