helloworld
helloworld

Reputation: 169

How does Django find template?

Below is my urls.py in mysite/mysite/settings.py

urlpatterns = [
    path('', TemplateView.as_view(template_name='homepage/main.html')),
    path('admin/', admin.site.urls), # add something
    path('polls/', include('polls.urls')),
    path('hello/', include('hello.urls')),
    path('accounts/', include('django.contrib.auth.urls')),  # Add, Search how does djnago find template.
    path('autos/', include('autos.urls')),
]

If some user request www.mysite.com/accounts/login

This request go to 'django.contrib.auth.urls' in there request go to path('login/', views.LoginView.as_view(), name='login') not in django/contrib/auth/urls.py..

But my login template is in mysite/homepage/templates/registration/login.html And below is my login.html

{% extends "base_bootstrap.html" %}

{% block content %}

{% if form.errors %}
  <p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url 'login' %}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn btn-primary" value="Login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}

It works well. so I don't know how Django find my login.html

How does Django find my login.html?

Upvotes: 1

Views: 272

Answers (1)

FlipperPA
FlipperPA

Reputation: 14361

Django has two main ways it will look for templates, defined the settings. I'll show an example.

from pathlib import Path

BASE_DIR = Path(__file__).resolve(strict=True).parent.parent + '/'

INSTALLED_APPS = [
    'website',
    'users',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR + 'templates',
            '/var/my_other_templates',
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            # ... some options here ...
        },
    },
]

In this example, let's say we are using a TemplateView with the attribute template_name = 'users/login.html', or {% include "users/login.html" %} in a template. Either way, the search will be the same.

  • The first is through the list of directories provided in DIRS, which it will check in order. If it finds a file called login.html at ./templates/users/login.html, it will use that template and stop looking. Otherwise, it will look for /var/my_other_templates/users/login.html.
  • If it doesn't find the template in either location, it will move on to your apps if APP_DIRS is set to True. First, it will look in ./website/templates/users/login.html, and failing that, ./users/templates/users/login.html.

If it doesn't find the template in any of those locations in this example, it will return a TemplateNotFound error, and the error will show all the directories in which Django looked for the template.

If you're using Django's internal apps, it will pull the templates from those apps if you haven't overridden them.

Upvotes: 3

Related Questions