【问题标题】:Python; Django adding characters to path name causing OS error 22Python; Django在路径名中添加字符导致操作系统错误22
【发布时间】:2017-06-12 01:22:49
【问题描述】:

我一直在尝试让 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)

非常感谢您的帮助!

【问题讨论】:

    标签: python django web filepath


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-04-21
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多