简体   繁体   English

Django主页找不到模板

[英]template not found for Django homepage

I'm still new to Django and I am trying to create a small website as practice. 我还是Django的新手,我正在尝试创建一个小型网站作为练习。 However I am currently running into this error. 但是我目前遇到这个错误。 If someone could explain where I went wrong and teach me how I can fix this that would be great! 如果有人可以解释我哪里出了问题并教我如何解决此问题,那就太好了! I'm new and the Documentation can be hard to read sometimes =[ 我是新手,有时可能很难阅读文档= [

Please let me know if there is anything else I need to add! 请让我知道是否还需要添加!

Environment:

Request Method: GET
Request URL: http://localhost:8000/home/

Django Version: 1.5.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')

Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
/home/bradford/Development/Django/pub_pic/~/Development/Django/pub_pic/templates/homepage_template/home.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
/home/bradford/Development/Django/django_1.5.1/local/lib/python2.7/site-packages/django/contrib/auth/templates/homepage_template/home.html (File does not exist)



Traceback:
File "/home/bradford/Development/Django/django_1.5.1/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/bradford/Development/Django/pub_pic/homepage/views.py" in index
  9.    return render(request,'homepage_template/home.html')
File "/home/bradford/Development/Django/django_1.5.1/local/lib/python2.7/site-packages/django/shortcuts/__init__.py" in render
  53.     return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/home/bradford/Development/Django/django_1.5.1/local/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  170.         t = get_template(template_name)
File "/home/bradford/Development/Django/django_1.5.1/local/lib/python2.7/site-packages/django/template/loader.py" in get_template
  146.     template, origin = find_template(template_name)
File "/home/bradford/Development/Django/django_1.5.1/local/lib/python2.7/site-packages/django/template/loader.py" in find_template
  139.     raise TemplateDoesNotExist(name)

Exception Type: TemplateDoesNotExist at /home/
Exception Value: homepage_template/home.html

I have a template named home.html and it is in the directory pub_pic/templates/homepage_template/home.html 我有一个名为home.html的模板,它位于目录pub_pic/templates/homepage_template/home.html

My pub_pic urls.py: 我的pub_pic urls.py:

from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
    url(r'home/',include('homepage.urls', namespace = 'home')),
)

My homepage urls.py: 我的首页urls.py:

from django.conf.urls import patterns, url
from homepage import views

urlpatterns = patterns('',
    url(r'^$', views.index, name = 'index'),



)

homepage/views.py: homepage / views.py:

from django.http import HttpResponse
from django.template import RequestContext, loader
from django.shortcuts import render, render_to_response

#from homepage.models import 

def index(request):
#   template = loader.get_template('homepage/index.html')
    return render(request,'homepage_template/home.html')

In your settings.py file you should use below code. 在settings.py文件中,应使用以下代码。

#settings.py
import os
# Full filesystem path to the project.
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, "templates"),)

Please do not include the full path in settings as the accepted answer suggests. 不要按照接受的答案建议在设置中包含完整路径 This is the "anti-django" way of doing things, even if it does work. 即使它确实起作用,这也是“反Django”的处理方式。

In Django you can either have one templates folder for a project or one templates folder per app. 在Django中,您可以为一个项目提供一个模板文件夹,或者为每个应用程序提供一个模板文件夹。 The latter allows you to move apps from project to project (which is how they are supposed to work) but the former can provide simplicity for monolithic once-off projects. 后者允许您将应用程序从一个项目移动到另一个项目(这就是它们应该如何工作的方式),但是前者可以为整体一次性项目提供简化。

You DO NOT need to and should not specify the absolute path. 您不需要也不应该指定绝对路径。 In your settings, if you want a single templates directory for your project use something like: 在设置中,如果要为项目使用单个模板目录,请使用以下命令:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates')
,)

This is basically saying your templates are in a folder called 'templates' that is in the main BASE_DIR path. 这基本上是说您的模板位于主BASE_DIR路径中的“模板”文件夹中。 In this example that would be the root directory where the manage.py resides. 在此示例中,这将是manage.py所在的根目录。 Now just make a folder called 'templates' in this root directory and throw your HTML in there (arranged in subfolders if you like). 现在,只需在此根目录中创建一个名为“模板”的文件夹,然后将HTML放到该目录中即可(如果您愿意,可以将其放在子文件夹中)。

Templates can then be loaded as simply as 然后可以像以下一样简单地加载模板

templt = get_template('mytemplate.html)

Where it is presumed that mytemplate.html file resides directly in the templates/ folder off the root directory. 假定mytemplate.html文件直接位于根目录下的templates /文件夹中。 You can use subfolders and if you do you should specify them in the quotes eg 'mysubdir/mytemplate.html' 您可以使用子文件夹,如果需要,则应在引号中指定它们,例如“ mysubdir / mytemplate.html”

As an alternative, you can allow each app to have its own templates In this case you must have the following in settings: 或者,您可以允许每个应用程序都有自己的模板。在这种情况下,您必须在设置中包含以下内容:

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',

        ],

    },

},

]

The key here is 这里的关键是

'APP_DIRS': True,

This ( according to the Django docs ) instructs the system to look in each app for a 'templates' folder. 这( 根据Django docs )指示系统在每个应用程序中查找“ templates”文件夹。 Your project would then look something like (presuming a project name of mybigproject) 然后,您的项目将类似于(假设项目名称为mybigproject)

/home/myaccount/mybigproject/myapp1/templates/ / home / myaccount / mybigproject / myapp1 / templates /

and

/home/myaccount/mybigproject/myapp2/templates/ / home / myaccount / mybigproject / myapp2 / templates /

By contrast in the first scenario (single templates folder) it would just be 相比之下,在第一种情况下(单个模板文件夹)

/home/myaccount/mybigproject/templates/ / home / myaccount / mybigproject / templates /

However the important thing to take away is that you STILL REFERENCE IT AS : 但是,要带走的重要事情是您仍然引用它为

templt = get_template('mytemplate.html)

Django will search through all the app folders for you. Django将为您搜索所有应用程序文件夹。 If it still gives you a file not found error it is a configuration thing. 如果它仍然为您提供文件未找到错误,则是配置问题。

If you specify a full path, now you need to change that path as you move PC's (eg shared projects), projects or apps which is a disaster. 如果指定了完整路径,则现在需要在移动PC(例如共享项目),项目或应用程序时更改该路径,这是灾难。

You don't show the value of your TEMPLATE_DIRS setting. 您没有显示TEMPLATE_DIRS设置的值。 But looking at the error message, it looks like you're using ~/... there. 但是,查看错误消息,似乎您正在使用~/... Don't do that: use the full path - /home/bradford/Development/Django/pub_pic/templates . 不要那样做:使用完整路径- /home/bradford/Development/Django/pub_pic/templates

Installed Applications:
('homepage_template.apps.Homepage_templateConfig', #add this line
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles')

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

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