DEV Community

Buono
Buono

Posted on • Updated on

How to Create a Template in Django

In Django, you can create views and templates as you like. Here's a simple guide.

How to Create a Template

1. Add a path to urls.py

Add the following section to urlpatterns in urls.py:

from .views import MyClass  # Add this

urlpatterns = [
    path('XXXurl/', MyClass.as_view(),  # Add this
]
Enter fullscreen mode Exit fullscreen mode

2. Create a file for the view

As shown below, create a view file, import TemplateView, and specify hello.html as the template (to be created later).

from django.views.generic import TemplateView  # Add this

class MyClass(TemplateView):  # Add this
    template_name = 'hello.html'  # Add this
Enter fullscreen mode Exit fullscreen mode

3. Create the template file

First, create a templates directory at the project's root, and within it, create a file named hello.html.

cd /your/project/path
mkdir templates
touch templates/hello.html
Enter fullscreen mode Exit fullscreen mode
Hello World!
Enter fullscreen mode Exit fullscreen mode

4. Modify setting.py

By default, the template file directory is not registered, so modify the file as follows:

TEMPLATES = [
    'DIRS' = [BASE_DIR / 'templates'],  # Modify
Enter fullscreen mode Exit fullscreen mode

Verification

Run the following, and the content of hello.html should be displayed in the browser.

python3 manage.py runserver
Enter fullscreen mode Exit fullscreen mode

image.png

How to Handle TemplateDoesNotExist Error

An error you'll likely encounter when working with templates.
image.png

Since it says "Template does not exist," check the following:

  • Is the content of DIRS in settings.py's TEMPLATES correct?
  • Does the file name for the view match the template name registered in views.py?
  • Does the class name defined in views.py match the class name imported in urls.py?

That's it.

Top comments (0)