Django入门与实践:三、第一个Template

本文介绍如何使用Django框架搭建一个简单的博客网站,包括配置URL、创建视图、渲染模板等关键步骤。

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

在根urls.py中引入include;

根urls.py中url函数第二个参数改为:include("blog.urls")

具体:修改myblog/myblog/urls.py文件为

"""myblog URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')), # 引入'blog/urls'模块
]

在app目录下创建urls.py文件,格式与根urls.py相同 ; 

具体:blog文件夹下增加urls.py文件

from django.urls import path
from . import views

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

启动服务器:

python manage.py runserver 8080

在浏览器地址栏中输入localhost:8080/blog/index/即可浏览。

注意:

根urls.py针对APP配置的URL名称,是该APP所有URL的总路径;

开发第一个template:

步骤:

1、在app目录下创建 名为templates的目录;

2、在该目录下创建html文件;

3、在views.py中返回render()。

myblog/blog/views.py:

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
    #return HttpResponse("Hello world!")
    return render(request, 'index.html', {'hello': 'hello, blog!'})

myblog/blog/templates/index.html:

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

DTL初步使用:

render()函数中支持dict类型参数;

该字典是后台传递到模板的参数,键为参数名;

在模板中使用{{参数名}}来直接使用

Django查找查找Template:

Django按照INSTALLED_APPS中添加的顺序查找TEMPLATES;

不同APP下TEMPLATES目录中的同名.html文件会造成冲突。

解决TEMPLATES冲突的方案:

在APP的TEMPLATES目录下创建以APP为名称的目录;

将html文件放入新创建的目录下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值