2013-06-18 15 views
10

Ich bin neu in Django. Ich habe einen Ordner namens templates in meinem Projekt und "base.html" drin, es funktioniert gut. Aber wenn ich mache neue Ordner innerhalb Vorlagen begrüßen und dann „home.html“ und ich schreibe ein paar Zeilen Code in meiner views.py Datei alsVorlage existiert nicht

from django.shortcuts import render_to_response 

def hello(request): 
    return render_to_response('welcome/home.html') 

und settings.py umfasst

# Django settings for Telecom project. 

DEBUG = True 
TEMPLATE_DEBUG = DEBUG 

import os 
#BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 

PROJECT_DIR = os.path.dirname(__file__) 

ADMINS = (
    # ('Your Name', '[email protected]'), 
) 


MANAGERS = ADMINS 

DATABASES = { 
    'default': { 
     'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 
     'NAME': 'mysql',      # Or path to database file if using sqlite3. 
     'USER': 'root',      # Not used with sqlite3. 
     'PASSWORD': '',     # Not used with sqlite3. 
     'HOST': '127.0.0.1',      # Set to empty string for localhost. Not used with sqlite3. 
     'PORT': '3306',      # Set to empty string for default. Not used with sqlite3. 
    } 
} 

# Hosts/domain names that are valid for this site; required if DEBUG is False 
# See https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/#allowed-hosts 
ALLOWED_HOSTS = [] 

# Local time zone for this installation. Choices can be found here: 
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name 
# although not all choices may be available on all operating systems. 
# On Unix systems, a value of None will cause Django to use the same 
# timezone as the operating system. 
# If running in a Windows environment this must be set to the same as your 
# system time zone. 
TIME_ZONE = 'America/Chicago' 

# Language code for this installation. All choices can be found here: 
# http://www.i18nguy.com/unicode/language-identifiers.html 
LANGUAGE_CODE = 'UTC' 

SITE_ID = 1 

# If you set this to False, Django will make some optimizations so as not 
# to load the internationalization machinery. 
USE_I18N = True 

# If you set this to False, Django will not format dates, numbers and 
# calendars according to the current locale 
USE_L10N = True 

# Absolute filesystem path to the directory that will hold user-uploaded files. 
# Example: "/home/media/media.lawrence.com/media/" 
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') 


# URL that handles the media served from MEDIA_ROOT. Make sure to use a 
# trailing slash. 
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/" 
MEDIA_URL = 'http://localhost:8000/media/admin/' 

# Absolute path to the directory static files should be collected to. 
# Don't put anything in this directory yourself; store your static files 
# in apps' "static/" subdirectories and in STATICFILES_DIRS. 
# Example: "/home/media/media.lawrence.com/static/" 
STATIC_ROOT = '' 

# URL prefix for static files. 
# Example: "http://media.lawrence.com/static/" 
STATIC_URL = '/static/' 

# URL prefix for admin static files -- CSS, JavaScript and images. 
# Make sure to use a trailing slash. 
# Examples: "http://foo.com/static/admin/", "/static/admin/". 
ADMIN_MEDIA_PREFIX = '/static/admin/' 

# Additional locations of static files 
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static". 
    # Always use forward slashes, even on Windows. 
    # Don't forget to use absolute paths, not relative paths. 
) 

# List of finder classes that know how to find static files in 
# various locations. 
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder', 
    'django.contrib.staticfiles.finders.AppDirectoriesFinder', 
# 'django.contrib.staticfiles.finders.DefaultStorageFinder', 
) 

# Make this unique, and don't share it with anybody. 
SECRET_KEY = 'b9_hyqe*b&ra_&wlm5a9xas_ag#5mjv-dy=to%hdk_u-#xvn*l' 

# List of callables that know how to import templates from various sources. 
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader', 
    'django.template.loaders.app_directories.Loader', 
# 'django.template.loaders.eggs.Loader', 
) 

TEMPLATE_DIRS = (  
        os.path.join(PROJECT_DIR, 'templates'), 

) 

print PROJECT_DIR 
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware', 
    'django.contrib.sessions.middleware.SessionMiddleware', 
    'django.middleware.csrf.CsrfViewMiddleware', 
    'django.contrib.auth.middleware.AuthenticationMiddleware', 
    'django.contrib.messages.middleware.MessageMiddleware', 
) 

ROOT_URLCONF = 'Telecom.urls' 

INSTALLED_APPS = (
    'django.contrib.auth', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.sites', 
    'django.contrib.messages', 
    'django.contrib.staticfiles', 
    # Uncomment the next line to enable the admin: 
    'django.contrib.admin', 
    # Uncomment the next line to enable admin documentation: 
    'django.contrib.admindocs', 
    'welcome', 
) 

# A sample logging configuration. The only tangible logging 
# performed by this configuration is to send an email to 
# the site admins on every HTTP 500 error. 
# See http://docs.djangoproject.com/en/dev/topics/logging for 
# more details on how to customize your logging configuration. 
LOGGING = { 
    'version': 1, 
    'disable_existing_loggers': False, 
    'handlers': { 
     'mail_admins': { 
      'level': 'ERROR', 
      'class': 'django.utils.log.AdminEmailHandler' 
     } 
    }, 
    'loggers': { 
     'django.request': { 
      'handlers': ['mail_admins'], 
      'level': 'ERROR', 
      'propagate': True, 
     }, 
    } 
} 

aber Der Fehler zeigt

TemplateDoesNotExist at /hello/ 
/welcome/home.html 
Request Method: GET 
Request URL: http://localhost:8000/hello/ 
Django Version: 1.6 
Exception Type: TemplateDoesNotExist 
Exception Value:  
/welcome/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\\Telecom', 
'C:\\Python27\\lib\\site-packages\\distribute-0.6.35-py2.7.egg', 
'D:\\Bishnu\\BE\\4th year\\8th semester\\Major Project II\\Working\\Workspace\\Telecom', 
'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: Tue, 18 Jun 2013 17:09:07 +0545 

Wie kann ich es lösen?

+0

Jeder Grund, Django Entwicklungsversion zu verwenden? Dies wurde noch nicht veröffentlicht und kann Fehler enthalten. Hast du den letzten stabilen 1.5 ausprobiert? Es scheint zu versuchen, Ihre Vorlage an der Wurzel ('/') anstelle der Basispfade zu laden. Sind Sie sicher, dass Ihr 'PROJECT_DIR' korrekt ist und auf den absoluten Pfad zeigt? Probieren Sie 'print PROJECT_DIR' in' settings.py' aus, um den Inhalt herauszufinden. Und was hast du als 'TEMPLATE_LOADERS' festgelegt? – gertvdijk

+0

Zeigen Sie das Baumverzeichnis an, in dem sich Ihre Vorlage "welcome/home.html" befindet. Schreibe auch deine settings.py Datei. – lalo

+0

PROJECT_DIR zeigt D: \ Bishnu \ BE \ 4. Jahr \ 8. Semester \ Hauptprojekt II \ Working \ Workspace \ Telecom \ Telecom –

Antwort

11

Dieser Fehler auf settings.py wie unten

import os.path 
Temp_Path = os.path.realpath('.') 
... 
STATIC_ROOT = ''  
# URL prefix for static files. 
# Example: "http://example.com/static/", "http://static.example.com/" 
STATIC_URL = '/static/' 
... 
TEMPLATE_DIRS = (
    Temp_Path +"/template" 
) 

dann innerhalb Vorlagenordner und CSS/JavaScript-Datei in statischen Ordner alle Ihre Vorlage setzen kann auf die falsche Vorlage Verzeichnisse auf Grund entsteht die in Ihrem Versuchen etwas Abwechslung liegt Anwendungsordner. Hoffe das wird dein Problem lösen.

My suggestion don't put template folder inside application folder

Django wird die erste Vorlage wählt sie deren Namen finden übereinstimmt und , wenn Sie in einer anderen Anwendung, Django zwischen ihnen zu unterscheiden wären nicht in der Lage eine Vorlage mit dem gleichen Namen hatten. Wir müssen in der Lage auf Django auf der rechten Seite, und der einfachste Weg, um sicherzustellen, dass dies ist durch Namespacing ihnen. Das heißt, indem Sie diese Vorlagen innerhalb von ein anderes Verzeichnis für die Anwendung selbst benannt.

0

nehme an, dass Sie ein django Projekt "my_project" hace und die Anwendung "app_1" und "app_2"

my_project 
    -- my_project 
    -- manage.py 
    welcome 
     -- __init__.py 
     templates    
      -- home.html 
     -- models.py 
     -- views.py 

    app_1 
     -- __init__.py 
     templates 
      welcome 
       -- home.html 
     -- models.py 
     -- views.py 
    app_2 
     templates 
      a_subfolder 
       -- home.html 
     -- __init__.py 
     -- models.py 
     -- views.py 

jetzt, wenn Sie einige Einstellungen haben mögen.

#... 
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader', 
    'django.template.loaders.app_directories.Loader', 

) 
#... 

INSTALLED_APPS = (
    'app_2', 
    'app_1', 
    'welcome', 
    #... 
) 

#... 

django wird das tun: Wenn Sie render_to_response('welcome/home.html') nennen (ich glaube, dass einige params fehlen), django wird in einigen einigen "welcome" -Ordner in ALLEN aplications (in diesem auf "home.html" Datei suchen case "app_1" und "app_2"), die einen "templates" -Ordner haben. (Das ist eine Konvention)

EDIT

Ich habe Sie fügte hinzu: "welcome" App.

Sie haben die Methode aufrufen, ohne App-Namen render_to_response('home.html')

+0

Ich habe schon getan was du beantwortet hast und willkommen ist die einzige App, die ich erstellt habe die ich bereits aufgenommen habe. Aber nicht die Lösung zu bekommen. –

+0

Haben Sie den Ordner "Vorlagen" in "Willkommen" App? Hast du 'render_to_response ('home.html')' '? – lalo

+0

Ich habe die Ordnervorlagen nur in meinem Hauptprojektordner Telecom gemacht, nicht in irgendeiner App, an derselben Stelle, an der manage.py lokalisiert. Ich habe es in Eclipse getan. –

-3

Haben Sie die Datei erstellt __init__.py in Ihrem welcome Ordner?

+0

'__init __. Py'? – lalo

+0

ja. Ohne diese Datei ist keine Vorlage im Ordner verfügbar. – kanishk

+0

Ja, ich weiß, schreibe einfach die nichtcores :) – lalo

3

Versuchen Sie folgendes:

In Ihrem settings.py Datei ersetzen

 

TEMPLATE_DIRS = (  
        os.path.join(PROJECT_DIR, 'templates'), 

) 
 

mit

 

TEMPLATE_DIRS = (  
        os.path.join(PROJECT_DIR, 'templates'), 
        os.path.join(PROJECT_DIR, 'templates/welcome') 

) 
 

Dann im Code, rufen Sie einfach render_to_response ("home.html")

Das sollte Ihr Problem lösen.

2

Sie verwenden können: in settigns.py

TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/'),) 


STATICFILES_DIRS = (
    'static', 
) 
14

Für Django 1.8 oder höher Sie haben die Vorlage Pfad in der DIRS Schlüssel TEMPLATES Liste als eine Liste von Zeichenfolge hinzuzufügen.

TEMPLATES = [ 
    { 
     'BACKEND': 'django.template.backends.django.DjangoTemplates', 
     'DIRS': ['Secondjango/Secondjango/templates/welcome'],  #<<<<<<<<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', 
      ], 
     }, 
    }, 
] 
1

Überprüfen Sie, ob in "hello.html" ein Include-Tag vorhanden ist, dem ein Dateipfad zugewiesen wurde, der nicht existiert. Der Fehler ausgelöst kommt gleich: -

TemplateDoesNotExist an/hallo/ /welcome/home.html

0

Für Django 1.8 oder höher nur folgendes hinzufügen in VORLAGEN DIR Variablenliste in Einstellungsdatei

TEMPLATES = [ 
{ 
    'BACKEND': 'django.template.backends.django.DjangoTemplates', 
    'DIRS': ['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', 
     ], 
    }, 
}, 
] 

Diese Eigenschaft verweist auf Template-Verzeichnis 'DIRS': ['templates'],

0

für Django 2.0, herausgegeben ich den Wert DIRS von VORLAGEN in f Einstellung ile den Eintrag Verzeichnis des Projektes:

TEMPLATES = [ 
{ 
    'BACKEND': 'django.template.backends.django.DjangoTemplates', 
    'DIRS': ['.'], # here set DIRS to project's entry directory 
    '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', 
     ], 
    }, 
}, 

]

und das gelöste Problem auf Mac und Windows-Systemen.

0

Bitte überprüfen Sie, ob Sie Ihre neue Anwendung in der settings.py Datei unter INSTALLED_APPS

Django stellt alle ‚Vorlagen‘ Ordner von allen Anwendungen in Ihrem Projekt zu einem einzigen ‚Vorlagen‘ Ordner hinzugefügt haben.

Denken Sie daran, ein separates Verzeichnis im Vorlagenordner Ihrer Anwendungen zu erstellen, damit das Django-Framework die gesuchte Vorlage leichter finden kann.