蟒蛇; Django在路径名中添加字符导致操作系统错误22

时间:2017-06-12 01:22:50

标签: python django web filepath

我一直试图让django渲染我创建的模板。起初它说模板不存在,但是一旦我修复了错误,它现在就在路径中添加了字符而没有找到模板。

路径应该是: C:\\Users\\ABC\\Desktop\\science_crowd\\Lightweight_Django\\placeholder\\home.html

然而错误说它无法找到: C:\\Users\\Benjamin\\Desktop\\science_crowd\\Lightweight_Django\\placeholder\\:\\home.html

它无缘无故地添加了冒号和另一个反斜杠。

此项目的设置如下:

ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '127.0.0.1').split(',')

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

settings.configure(
    DEBUG = DEBUG,
    SECRET_KEY = SECRET_KEY,
    ALLOWED_HOSTS = ALLOWED_HOSTS,
    ROOT_URLCONF = __name__,
    MIDDLEWARE_CLASSES = (
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ),
    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles'
    ),
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': os.path.join(BASE_DIR, 'templates'),
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    "django.contrib.auth.context_processors.auth",
                ],
            },
        },
    ],
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
    ),
    STATIC_URL = '/static/',
)

尝试呈现模板的视图:

def index(request):
    example = reverse('placeholder', kwargs = {'width': 50, 'height': 50})
    context = {
        'example': request.build_absolute_uri(example)
    }
    dir = os.path.join(BASE_DIR, 'templates')
    return render(request, 'home.html', context = context)

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:2)

DIRS设置需要列表或元组。试试:

'DIRS': [os.path.join(BASE_DIR, 'templates')],