django配置templates为html目录

本文档详细介绍了如何在Django项目中设置templates作为HTML文件的根目录,包括创建App、编辑settings.py、建立templates文件夹结构、配置settings.py、定义views.py中的请求处理以及urls.py的路由设定。遵循这些步骤,您将能够成功运行服务器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 创建App( 项目创建完成的基础之上)

startapp first(appname)

(执行于在pycharm的tools工具中run manage.py)

2. settings.py,加入 app


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'first',#new
]

3.创建templates文件夹 /结构如下

  • musevery #project
    • musevery #
    • templates #html根目录
      • index.html # 默认首页(注意css,js引入文件路径static/css/style.css)
      • static #静态文件(css,js,img等)
        -css
        -js
        -img
    • first #app

4. settings.py 配置html文件根目录

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

#新增
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "templates/static"),
]

5. views.py定义请求

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt #解决post请求验证问题
def index(request):
    return render(request, 'index.html')

6. urls.py 配置路由


from django.conf.urls import url
from django.contrib import admin
from first import views as first_views #new

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', first_views.index,name='index'),#new
]

至此可以runserver

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值