Search code examples
pythondjangodjango-templatesdjango-generic-views

unable to shift pages from homepage to about page


I am trying to create a small web application with django and I am a novice in this I am trying to create a homepage and a about button on homepage that reloads the page to about page

This is my index.html

<!DOCTYPE html>
<html>
<head>
  <title>Simple App</title>
<h1> Testing the simple app</h1>
</head>
<body>
  <a href="/about/">About </a>
</body>
</html>

This is my about.html

<!DOCTYPE html>
<html>
<head>
  <title>Simple App</title>
<h1> Testing the simple app</h1>
</head>
<body>

  This is the about page
</body>
</html>

This is my views.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.views.generic import TemplateView

# Create your views here.

class HomePageView(TemplateView):
    def get(self, request, **kwargs):
        return render(request, 'index.html', context=None)

# Add this view
class AboutPageView(TemplateView):
    template_name = "about.html"

and urls.py

from django.conf.urls import url
from django.contrib import admin
from homepage import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', views.HomePageView.as_view()),
    url(r'^about/$',views.AboutPageView.as_view()),
]

However when i click on about button nothing happens


Solution

  • In urls.py you can directly tell the Generic template view the name of the layout to use like this:

    from django.urls import include, path
    from django.views.generic import TemplateView
    
    urlpatterns = [
        path("", TemplateView.as_view(template_name="homepage.html"), name="home"),
        path("about/", TemplateView.as_view(template_name="about.html"), name="about" ]
    

    Using named urls is better than directly coding the url, as they may change in the future.

    Then in homepage.html refer to it as:

    <a href="{% url 'about' %}">About</a>
    

    Update:

    If you can't use path and want to use url:

    url(r'^$',TemplateView.as_view(template_name="homepage.html"), name="home"),
    url(r'^about/$',TemplateView.as_view(template_name="about.html"), name="about"),