简体   繁体   English

Django 和 Tailwind 'TemplateDoesNotExist' 错误

[英]Django and Tailwind 'TemplateDoesNotExist' error

I am following this tutoiral: https://www.ordinarycoders.com/blog/article/django-tailwind我正在关注这个教程: https://www.ordinarycoders.com/blog/article/django-tailwind

I have a django project called 'project' with two apps in it 'app' and 'main'.我有一个名为“project”的 django 项目,其中包含两个应用程序“app”和“main”。 I'm trying to load 'main > template > main > home.html' .我正在尝试加载'main > template > main > home.html' but I get this error:但我收到此错误:

Internal Server Error: /
Traceback (most recent call last): 
  File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner     
    response = get_response(request)
  File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response 
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\project\main\views.py", line 5, in homepage
    return render(request = request, template_name="main/home.html")  
  File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\template\loader.py", line 61, in render_to_string  
    template = get_template(template_name, using=using)
  File "C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\lib\site-packages\django\template\loader.py", line 19, in get_template      
    raise TemplateDoesNotExist(template_name, chain=chain)
django.template.exceptions.TemplateDoesNotExist: main/home.html       
[17/Nov/2021 11:49:03] "GET / HTTP/1.1" 500 80436

Following the tutorial, I have in my 'settings.py' :按照教程,我有我的 'settings.py'

"""
Django settings for project project.

Generated by 'django-admin startproject' using Django 3.2.9.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = _____________________[blanked out]_____________________

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'tailwind',
    'app',
    'main',
]

TAILWIND_APP_NAME = 'app'
NPM_BIN_PATH = r"C:\Program Files\nodejs\npm.cmd"

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

TAILWIND_APP_NAME = 'app'

ROOT_URLCONF = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\project\main\template'],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'project.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

In my project>urls.py I have:在我的项目>urls.py我有:

from django.contrib import admin
from django.urls import path, include  #add include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include ('main.urls')),   #add this
]

In my main>urls.py :在我的main>urls.py中:

from django.urls import path
from . import views

app_name = "main"   


urlpatterns = [
    path("", views.homepage, name="homepage"),
]

In main>views.py I havemain>views.py我有

from django.shortcuts import render

# Create your views here.
def homepage(request):
    return render(request = request, template_name="main/home.html")

I've tried to add the template directory of main into DIRS in settings.py follwing this other Stack link: Django: TemplateDoesNotExist at / home.html in my project我已经尝试将 main 的模板目录添加到 settings.py 中的 DIRS 中,然后按照其他堆栈链接: Django: TemplateDoesNotExist at / home.html 在我的项目中

But I haven't been able to open the html file.但我一直无法打开 html 文件。

Any help greatly appreciated.非常感谢任何帮助。 Thanks谢谢

Hey change this line in your settings.py from this嘿,在你的settings.py中改变这一行

        'DIRS': ['C:\Users\Kaij\Documents\djangoTests\djangoTailwind2\env\project\main\template'],

to this对此

 [BASE_DIR/ 'templates']

and then in your main directory create a folder called templates and within that folder create another folder called main and that is where your home.html goes into.然后在您的main目录中创建一个名为templates的文件夹,并在该文件夹中创建另一个名为 main 的文件夹,这就是您的home.html所在的位置。 so something like this所以像这样

project -> main -> templates -> home.html

and in your folder called main, create a urls.py and add these lines在名为 main 的文件夹中,创建一个urls.py并添加这些行

from django.urls import path
from .views import some_view_name

urlpatterns = [
    path('', some_view_name, name='home-view')
]

then in main -> views.py add this line to然后在 main -> views.py 中将这一行添加到

from django.shortcuts import render
def some_view_name(request):
    return render(request, "main/home.html")

that should some the problem for you.那应该给你一些问题。

your directory structure should look like something like this你的目录结构应该是这样的

project 
    -> project
          urls.py
           ...
    -> main
          ->templates
            -> main
                 -> home.html
   manage.py
   ...

If this solves your problem please don't forget to accept it as the correct answer.如果这解决了您的问题,请不要忘记接受它作为正确答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM