[Django]-Display static page in Django

4👍

First of all, what is the stacktrace from the 500 error saying that the error may be? You may be using Django 1.6 and the call to direct_to_template is deprecated.

On Django 1.5 or newer you can use TemplateView

Here’s the example from the documentation

https://docs.djangoproject.com/en/dev/topics/class-based-views/

from django.conf.urls import patterns
from django.views.generic import TemplateView

urlpatterns = patterns('',
    (r'^about/', TemplateView.as_view(template_name="about.html")),
)

You can use the direct_to_template view on Django 1.4 or older

Here’s the relevant documentation

https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-simple-direct-to-template

from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
    (r'^foo/$',             direct_to_template, {'template': 'foo_index.html'}),
    (r'^foo/(?P<id>\d+)/$', direct_to_template, {'template': 'foo_detail.html'}),
)

If it is the latter, I would use a module instead of string, (look at the import on the example).

Other than that, without the 500 details it will be shooting in the dark, you may not have the right template, or an incorrect path, or a million different things.

Bonus note

If you just want to serve static pages, it might be better to serve them through the actual webserver in front of django (nginx, apache, etc), specially if you are expecting a high volume of traffic.

1👍

If Your error is due to unable to find index.html

if yours is an app(ie: created by python manage.py startapp <app>) then:

Then django will search for template files in <app>/templates directory, if you added the app to INSTALLED_APPS in settings.py.

so you need to create a folder templates inside your <app> and put index.html inside it.

if you don’t have any apps, you want to add the template path manually :

open settings.py, then edit TEMPLATE_DIRS

TEMPLATE_DIRS = (
    # Put the full path of the template dir here, like "/home/html/django_templates" or
    # "C:/www/django/templates". 
)

0👍

In Django 1.5 or newer you can use the render function instead of direct_to_template:

from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
    url(r'^$', 'django.shortcuts.render', {'template_name': 'index.html'}),
)

Or if you prefer the more complex way :), you can use class-based TemplateView:

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

urlpatterns = patterns('',
    url(r'^$', TemplateView.as_view(template_name="index.html")),
)

Leave a comment