I am new to Django and when I run the project I get an error
Unfortunately, previous questions did not solve my problem.
TemplateDoesNotExist at /
blog/index.html
This is my folder structure:
country/
urls.py
wsgi.py
settings.py
blog/
migrations/
templates/
blog/
index.html
admin.py
models.py
tests.py
urls.py
views.py
manage.py
urls blog :
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.index, name='index'),
]
views blog
from django.shortcuts import render
def index(request):
return render(request,'blog/index.html')
settings
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
//snip
},
]
INSTALLED_APPS = [
'blog',
//snip
]
To solve this problem, after creating the template folder, I ran the migrate command once and the problem was solved
python manage.py migrate
Related
I have followed the steps from the django tutorial ( https://docs.djangoproject.com/en/4.1/intro/tutorial01/ ) and once I'd finished all the steps I stopped developing the project for 2 weeks at least without giving it much thought.
Once I've decided to check how the pages were looking like that's when I found this:
The admin page
And I don't know how I did it.
Here's how the documentation looks like:
meuSite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
polls/
migrations/
static/
templates/
admin/
base.html
polls/
detail.html
index.html
results.html
__init__.py
admin.py
apps.py
models.py
tests.py
urls.py
views.py
db.sqlite3
manage.py
SETTINGS:
meuSite/settings.py
INSTALLED_APPS = [
'polls.apps.PollsConfig',
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
URLS:
# meuSite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("polls/", include('polls.urls')),
]
# polls/urls.py
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:question_id>/', views.DetailView.as_view(), name='detail'),
path('<int:question_id>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote')
]
If there's something else that I didn't show that may have the root of the problem, please tell me
I tried solving it by deleting the templates/admin directory, but it didn't change how the page looks
I've been hitting a snag with my Django app. Running Python manage.py runserver in my development environment, I get this error:
django.core.excptions.ImproperlyConfigured. The TEMPLATE_DIRS setting must be a list or a tuple. After changing TEMPLATE_DIRS to a tuple in settings.py as this TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) I got :
TypeError('Invalid path type: %s' % type(value).__name__)TypeError: Invalid path type: tuple.
I got a similar response when I changed it to a list.
Meanwhile, running Python manage.py runserver outside the development environment I got:
expected str, bytes or os.PathLike object, not tuple on both times I changed TEMPLATE_DIRS to a list and tuple.
I should also add that my template files aren't loading. I get:
Using the URLconf defined in myProject.urls, Django tried these URL
patterns, in this order:
accounts/
admin/
The current path, index/, didn't match any of these
Here is the project tree:
|_______myApp
|______ |______pycache__
| |______migrations
| |________init__
| |______admin
| |______apps
| |______models
| |______tests
| |______urls
| |______views
|______myProject
| |________init__
| |______asgi
| |______settings
| |______urls
| |______wsgi
|______env
|______static
|______templates
|______myApp
|______index.html
|______signup.html
manage.py
myProject/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('accounts/', include('accounts.urls')),
path('admin/', admin.site.urls),
]
myApp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('signup/', views.signup, name='signup'),
]
views.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('signup/', views.signup, name='signup'),
]
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates'), ]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_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',
'django.template.context_processors.media',
], }, },]
I don't know how else to fix it.
TEMPLATE_DIRS is already a list, so it makes no sense to wrap that again in the list, you should define the TEMPLATES setting as:
TEMPLATES = [
{
# …,
'DIRS': TEMPLATE_DIRS,
# …
}
]
I'm not able to import my views in the app folder to the URLS of project folder. I've tried every possible methods like 'from . import views' or 'from newapp import views as newapp_views' and 2-3 more alternatives that I searched on the internet. My app name is newapp and project name is newproject. Please help me.
This is my models file:
from django.db import models
class User(models.Model):
first_name=models.CharField(max_length=128)
last_name=models.CharField(max_length=128)
email=models.EmailField(max_length=256, unique=True)
This is my URLS of newapp folder:
from django.conf.urls import url
from django.urls.resolvers import URLPattern
from .models import views
urlpatterns= [url(r'^$', views.users, name='users'),
]
This is my views of newapp folder:
from django.shortcuts import render
from .models import User
def index(request):
return render(request, 'newapp/index.html')
def users(request):
user_list=User.objects.order_by('first_name')
user_dict={'users': user_list}
return render(request, 'newapp/users.html', context=user_dict)
This is my URLS of newproect folder:
from django.contrib import admin
from django.urls import path,include
from newapp import views
urlpatterns = [
path('', views.index, name='index'),
path('users/',views.users, name="users"),
path('admin/', admin.site.urls),
]
This is my settings file:
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'newapp'
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'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',
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
You can't import your file like this: from newapp import views.
And from . import views will work only if your urls.py file is in your app folder, while Django by default put it inside your project folder.
If you choose to have separated urls.py files per app (which is a good practice, as your project could grow into many apps), you could do the following:
newapp/urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('users/',views.users, name="users"),
path('admin/', admin.site.urls)
]
newproject/urls.py
from django.urls import path, include
urlpatterns = [
path('', include('newapp.urls'))
]
This way you just include the app urls in the project url file, and you can use a path to prefix all the app urls (instead of a blank string as above).
I am trying to do a project for a blog by django 3.1.2 , but unable to link the templates.I tried fixing it with **'DIRS': [os.path.join(BASE_DIR, 'templates'),]** I cannot find the logic miss. The template does exist and when I review the code, the query is performing correctly. I'm at a loss.
my setting
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',
],
},
},
]
my blog urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('', include('posts.urls')),
path('admin/', admin.site.urls),
]
my posts urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
my posts views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request,'posts/index.html')
If your templates folder is in your application's directory
eg: app_name / templates / app_name /.html, then you do not need to add
'DIRS': [os.path.join(BASE_DIR, 'templates'),]'.
So, if your application name is my_posts, create a folder named templates in your application directory. Then again create a folder named my_posts(same as application name) in templates directory, and then inside it create all your html files. But remember in your views.py when you are rendering, you have to do it as such, 'my_posts/index.html'
You only need to add 'DIRS': [os.path.join(BASE_DIR, 'templates'),]' , if you have you template folder in your main/project directory.
I am new to Django. I use pydev eclipse as an IDE. First I created a project then an application welcome on that project. I made a folder named Templates within the project and make a file "home.html" and home.html contains
<div>
This is my first site
</div>
I modify the settings.py file as
TEMPLATE_DIRS = ("Templates")
INSTALLED_APPS = (
..........#all default items
'welcome', #the added one
)
views.py includes
from django.shortcuts import render_to_response
def home(request):
return render_to_response('home.html')
urls.py contains
from django.conf.urls import patterns, include, url
from welcome.views import home
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'MajorProject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^home/$', home),
)
then I run it as django project and open my browser and see on localhost:8000/home
it shows error
TemplateDoesNotExist at /home/
home.html
Request Method: GET
Request URL: http://localhost:8000/home/
Django Version: 1.6
Exception Type: TemplateDoesNotExist
Exception Value:
home.html
Exception Location: C:\Python27\django\template\loader.py in find_template, line 131
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
Python Path:
['D:\\Bishnu\\BE\\4th year\\8th semester\\Major Project II\\Working\\Workspace\\MajorProject',
'C:\\Python27\\lib\\site-packages\\distribute-0.6.35-py2.7.egg',
'D:\\Bishnu\\BE\\4th year\\8th semester\\Major Project II\\Working\\Workspace\\MajorProject',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\wx-2.8-msw-unicode',
'C:\\Windows\\SYSTEM32\\python27.zip']
Server time: Sun, 2 Jun 2013 14:25:52 +0545
Try to set Templates Directory on setting.py.
as
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__),'templates'),
)
If you're using Django 1.8+
You'll get this warning:
(1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_DIRS, TEMPLATE_DEBUG.
Add your template directory to the Base TEMPLATES setting under the DIRS dictionary
Like so:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
root("templates"), #### Here ####
],
'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',
],
},
},
]
in Django 1.9
in settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR+r'\templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
...
],
},
},
]
Directory with templates should be named templates, not Templates (even though on windows it may be the same). Also make sure, you have application in PYTHONPATH or the correct directory structure of your project and application like:
project/
project/
settings.py
...
welcome/
templates/
home.html
views.py
...
manage.py
Then you don't need to change TEMPLATE_DIRS because app_directories.Loader (enabled by default) will find the templates in your application.
Also of if you still want to change TEMPLATE_DIRS, use absolute paths, but preferred way is the app_directories.Loader.
check below steps to fix
step 1:
Inside templates, 'DIRS' : [ ], metion this:
'DIRS': [os.path.join(BASE_DIR, 'templates')],
step 2:
Go in your views.py file and look for template_name (check its spelling and also check did you mentioned the right html file here or not)
step 3:
Check in your urls.py file wether you mentioned the right template name or not in the path
format: urlpatterns = [ path(" ", class name or function name, name = template name)
BASE_DIR = Path(file).resolve().parent.parent
This is default directory code by Django
And looks like this
C:\user\pc_name\django_project
But if you delete last .parent it will looks like this
C:\user\pc_name\django_project\django_project
So new BASE_DIR code which is this
BASE_DIR = Path(file).resolve().parent
Add this variable to TEMPLATE_DIR
TEMPLATE_DIR = os.path.join(BASE_DIR, 'template")
And last code define this
C:\user\pc_name\django_project\django_project\template
In the end safely uptade DIRS
'DIRS': 'TEMPLATE_DIR'
Hope you did