Django Noob URL to from Root Page to sub Page

642 views Asked by At

I have a Django project where I want to use an app for all the sites web pages. My project looks like this:

project
  src
    project
      urls.py
      views.py
      ...
    web
      migrations #package
      urls.py
      views.py
      ...
      templates
        web
          index.html # I want this to be my root page
          page2.html # This is the second page I'm trying to link to

I am trying to create a link in index.html that will take me to page2.html. This is what I am doing

In project->urls.py I have url(r'^$', include('web.urls', namespace="web")),. This should direct all page requests going to url http://127.0.0.1:8000/ to page index.html

project->views.py is empty because I want all web pages served up by the web app.

In web->urls.py I have url(r'^$', views.index, name='home_page') which relates to web->views.py and the function

def index(request):
   print("Main index Page")
   return render(request, 'web/index.html', {})

Which returns the correct page.

This works fine until I add the link to index.html for page2.html. The link looks like this: {% url 'web:page2' %}. I update web->urls.py. I add the following function into web->views.py:

def page2(request):
   print("Page2")
   return render(request, 'web/page2.html', {})

Now I get

Reverse for 'page2' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['$page2/?$']

With the '{% url 'web:page2' %}' line highlighted.

When I remove the link everything works fine. What is wrong with my logic/setup?

1

There are 1 answers

0
Brandon Taylor On BEST ANSWER

You need to add an additional URL pattern:

urls = [
    url(r'^page2/$', views.page2, name='page2'),
    url(r'^$', views.index, name='home_page'),
]

or alternatively, pass a parameter you can use to identify the page to be rendered to the view. Currently, you aren't mapping a URL to the function you want to call when the URL is matched for page2, just the home page.