问题
My templates are not recognized and I'm getting the following error.
os.path.dirname(__file__)+'\\template' NameError: name 'os' is not defined
The code which I have used in settings is:
os.path.dirname(__file__)+'\\template'
what should I do now.
回答1:
os module is missing You have used it without importing
Add this in your settings.py
import os
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)
and place all your templates under templates folder in your project
and you can use absolute paths like linux(/home/your_project/../templates) in windows ("C:/your_project/../templates") but it is not good practice
回答2:
You could see the relevant knowledge in Definitive Guide to Django Page 99:
import os.path
TEMPLATE_DIRS =(os.path.join(os.path.dirname(__file__),'templates').replace('\\','/'),)
Where explains how it works
This example uses the “magic” Python variable file, which is automatically set to the file name of the Python module in which the code lives. It gets the name of the directory that contains settings.py (os.path.dirname), joins that with templates in a cross-platform way (os.path.join), then ensures that everything uses forward slashes instead of backslashes (in the case of Windows).
回答3:
Import the module os
import os
来源:https://stackoverflow.com/questions/13927643/how-to-give-the-path-for-template-directory