Django 创建项目之视图和模板
目录
Django 简单请求案例
Django 视图(views)
Django 模板(templates)
Django view、template、url简单书写
1. 配置模板文件路径
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',
],
},
},
]
2. 模板文件templates/index.html,用于展示数据。
<p>{{ name }}</p>
技巧:生成模板
! + enter
3. 视图文件app/views.py
def index(request):
name = 'hello world!'
return render(request, "templates/index.html", {"name": name})
4. 路由app/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'), # FBC
# path('', views.Index.as_view(), name='index'), # CBV
]
Django 模板(Django模板语言DTL)
参考Django官网:https://docs.djangoproject.com/zh-hans/3.2/topics/templates/
参考:https://www.runoob.com/django/django-template.html
模板语言:https://www.cnblogs.com/CongZhang/p/5944463.html
Django 视图(view)
请求对象:HttpRequest(简称request)
Django中,一个页面被请求时,Django会创建一个HttpRequest对象,该对象包含了请求的元数据。
请求到达Django中的视图函数,并将HttpRequeset作为视图函数的第一个参数,然后视图函数返回一个HttpResponse对象。
1. GET
request.GET 获取的数据类型是QueryDict,类似字典的对象,包含http get请求的所有参数。
get():返回字符串,如果该键对应多个值,取该键的最后一个值。
实例:
def index(request):
info = request.GET.get("name") # request get content
return render(request, "home.html", {"name": info})
2. POST
request.POST数据类型式QueryDict,类似字典对象,包含HTTP POST的所有参数。
常用于form表单,form表单里的标签name属性对应参数的键,value属性对应参数的值。
get():返回字符串。
def index(request):
info = request.POST.get("name") # request get content
return render(request, "home.html", {"name": info})
3. body
数据类型式二进制节流,是原生请求体里的参数内容,在HTTP中用于POST,因为GET没有请求体。
在HTTP中不常用,而在处理非HTTP形式的报文时非常有用,列如:二进制图片、XML、json等。
def index(request):
info = request.body # request get content
return render(request, "home.html", {"name": info})
4. path
获取URL中的路径部分,数据类型时字符串。
def index(request):
info = request.path # request get content
return render(request, "home.html", {"name": info})
5. method
获取当前请求的方式,数据类型时字符串,且结果为大写。
def index(request):
info = request.method# request get content
return render(request, "home.html", {"name": info})
响应对象:HttpResponse
响应对象主要有三种形式:HttpResponse()、render()、redirect()。
HttpResponse():返回文本,参数为字符串,字符串中写文本内容。字符串中有html标签也可以渲染。
def index(request):
return HttpResponse("<p>hello world</p>")
render():返回文本,第一个参数为request,第二个参数为字符串(页面名),第三个参数为字典(可选参数,用于向页面传递参数,键为页面中参数名,值为views视图中参数名)
def index(request):
info = request.method# request get content
return render(request, "home.html", {"name": info})
redirect():重定向,跳转新页面。参数为字符串,字符串中填写页面路径。一般用于form表单提交后,跳转新的页面。
def index(request):
return redirect("/templates/home.html")

浙公网安备 33010602011771号