OceanWP

Django templates

Estimated reading: 2 minutes

Django templates are a way to separate the presentation logic of a web application from the Python code that handles the backend logic. They allow developers to define the structure of the HTML pages that are returned to the user, and to insert dynamic content into those pages.

In Django, templates are typically stored in a “templates” directory at the root level of a project or app. The file structure should be like this:


- coreapp/
    - migrations/
        - __init__.py
        - 0001_initial.py
    - templates/
        - core/
            - index.html
            - navbar.html
            - footer.html     
    - admin.py
    - apps.py
    - models.py
    - views.py
    - urls.py

The next step is to In the settings.py file, you need to add the following code to tell Django where to find the template files:


    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

This tells Django to look for templates in the “templates” directory at the root level of the project and to also look for templates within each app’s subdirectory.

Example: Here is an example of a simple template that displays when a view function is called:


    def index_view(request):
        return render(request, 'core/index.html')
        

Django templates are very powerful and can be used to create complex dynamic web pages. These are the basics of how to use them, but there are many more features and capabilities that you can learn as you continue to develop with Django.

Publisher
Share this tutorial