Reputation: 45
this is current_datetime.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
it is now {{date time}}
</body>
</html>
this is templates in settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 is views.py
import datetime
from django.shortcuts import render
def current_datetime(request):
now=datetime.datetime.now()
return render(request,'mysite/template/current_datetime.html',{'datetime':now})
this is urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls,name="admin"),
path('current_datetime/',views.current_datetime,name="current_datetime"),
]
and this is my directory
but when i run server by "python manage.py run server" and go to this url:
http://127.0.0.1:8000/current_datetime/
i got this error:
TemplateDoesNotExist at /current_datetime/
Upvotes: 0
Views: 641
Reputation: 587
You had everything set up correctly except for a few things
To fix this problem you have to run
$ django-admin startapp "your_app_name"
And then add the app under INSTALLED_APPS
in settings.py
. Once that has been created, you can move the templates folder into the new app and then the URL route "/current_datetime.html"
should work. Django automatically goes through the template folders in every app, but if you don't have an app then it throws a TemplateDoesNotExist
error.
I'm glad I could help!
Upvotes: 1
Reputation: 587
I believe the template should be loading fine (assuming that you changed the folder name to templates
instead of template
, but it's the path that may be incorrect.
def current_datetime(request):
now=datetime.datetime.now()
return render(request, '/current_datetime.html', {'datetime':now})
This is because Django has already found your templates directory, so now you only need to specify the path to the file within the folder itself.
Upvotes: 1