Python3-Mac OS 手动创建Django项目(三)

我们手动创建好Django项目后发现没有自动生成templates模板目录(如果用pycharm创建的话,会自动生成这个目录)。我们只能手动进行创建。

 1、在项目目录下手动创建templates目录。然后再创建一个static目录用来存放静态资源文件。

2、目录创建后之后再配置一下settings.py文件,分别配置templates目录和static目录。

#模板配置
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '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',
            ],
        },
    },
]

STATIC_URL = '/static/'
STATICFILES_DIRS=[
os.path.join(BASE_DIR, 'static')
]

3、测试一下,能否成功。在新建的templates目录下新建一个index.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>
</head>
<body>
<p>
    hello, {{name}}
</p>
</body>
</html>

然后在urls.py中配置一下路由 

from django.urls import path
from App import views

urlpatterns = [
    path('index/', views.index, name='index')

]

 views.py配置对应的函数

def index(request):
    return render(request, "index.html", context={"title": 'django', "name": '大圣'})

4、启动项目,访问 127.0.0.1/index 恭喜你成功啦! 

参考:

原文地址:https://www.cnblogs.com/happyflyingpig/p/14328554.html