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
]
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
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
Hello World!
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
Verification
Run the following, and the content of hello.html
should be displayed in the browser.
python3 manage.py runserver
How to Handle TemplateDoesNotExist
Error
An error you'll likely encounter when working with templates.
Since it says "Template does not exist," check the following:
- Is the content of
DIRS
insettings.py
'sTEMPLATES
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 inurls.py
?
That's it.
Top comments (0)