22

i want to set a main page or an index page for my app. i tried adding MAIN_PAGE in settings.py and then creating a main_page view returning a main_page object, but it doesn't work Also, i tries to add in the urls.py a declaration like

(r'^$', index),

where indexshould be the name of the index.html file on the root (but it obviously does not work)

What is the best way to set a main page in a Django website?

thanks!

dana
  • 5,168
  • 20
  • 75
  • 116

4 Answers4

20

The new preferred way of doing this would be to use the TemplateView class. See this SO answer if you would like to move from direct_to_template.

In your main urls.py file:

from django.conf.urls import url
from django.contrib import admin
from django.views.generic.base import TemplateView

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # the regex ^$ matches empty
    url(r'^$', TemplateView.as_view(template_name='static_pages/index.html'),
        name='home'),
]

Note, I choose to put any static pages linke index.html in its own directory static_pages/ within the templates/ directory.

Community
  • 1
  • 1
ryanjdillon
  • 17,658
  • 9
  • 85
  • 110
  • 1
    It is not clear what the path to `static_pages/index.html` is here. I can't replicate this, it gives 'Template not found' errors. – user5359531 Nov 07 '18 at 16:54
  • I solved the issue by 1) setting `app_name = 'myapp'` in the main `urls.py`, 2) adding `myapp` to the `INSTALLED_APPS` in the main `settings.py`, 3) putting my template at `myapp/templates/myapp/index.html`, 4) updating the view to use `template_name = 'myapp/index.html'` – user5359531 Nov 07 '18 at 17:15
13

If you want to refer to a static page (not have it go through any dynamic processing), you can use the direct_to_template view function from django.views.generic.simple. In your URL conf:

from django.views.generic.simple import direct_to_template
urlpatterns += patterns("",
    (r"^$", direct_to_template, {"template": "index.html"})
)

(Assuming index.html is at the root of one of your template directories.)

mipadi
  • 398,885
  • 90
  • 523
  • 479
  • 4
    This solution has been deprecated. See the chosen answer at http://stackoverflow.com/questions/11428427/no-module-named-simple-error-in-django – Andy Swift Jan 13 '17 at 20:22
  • Preferred way of doing this is explained in below answer by ryanjdillon – Ayush Apr 19 '18 at 10:00
10

In case someone searching for an updated version of the answer..

from django.urls import re_path
from . import views

urlpatterns = [
    re_path(r'^$', views.index, name='index')
]

and in your views.py

def index(req):
    return render(req, 'myApp/index.html')
Dabees
  • 494
  • 4
  • 14
1

You could use the generic direct_to_template view function:

# in your urls.py ...
...
url(r'^faq/$', 
    'django.views.generic.simple.direct_to_template', 
    { 'template': 'faq.html' }, name='faq'),
...
Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
miku
  • 181,842
  • 47
  • 306
  • 310