Django视graph
视graph is Djangoapplication core, 它processingHTTPrequest并返回HTTPresponse. Django视graph可以 is function视graph or class视graph.
function视graph
function视graph is 最 simple 视graphclass型, 它 is a 接收HTTPrequest并返回HTTPresponse Pythonfunction.
# blog/views.py
from django.http import HttpResponse
from django.shortcuts import render
# simple 视graphfunction
def hello_world(request):
return HttpResponse("Hello, Django World!")
# using模板 视graphfunction
def post_list(request):
# 获取所 has 博客文章
posts = BlogPost.objects.all()
# 渲染模板并返回response
return render(request, 'blog/post_list.html', {'posts': posts})
class视graph
class视graph is 基于class 视graph, 它providing了更 many flexible性 and codereusability. Djangoproviding了 many 种 in 置 class视graph, such asListView, DetailView, CreateView, UpdateView, DeleteViewetc..
# blog/views.py
from django.views.generic import ListView, DetailView
from .models import BlogPost
# usingListView显示所 has 博客文章
class PostListView(ListView):
model = BlogPost
template_name = 'blog/post_list.html'
context_object_name = 'posts' # 模板inusing variable名
ordering = ['-pub_date'] # 按release日期降序sort
# usingDetailView显示单个博客文章
class PostDetailView(DetailView):
model = BlogPost
template_name = 'blog/post_detail.html'
URLrouting
URLrouting用于将URLpathmap to 相应 视graphfunction or class视graph.
applicationURLconfiguration
首先 in applicationTable of Contents under creationurls.pyfile, configurationapplication URLrouting:
# blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.PostListView.as_view(), name='post_list'),
path('post//', views.PostDetailView.as_view(), name='post_detail'),
path('hello/', views.hello_world, name='hello_world'),
]
URL模式in parameter说明:
<int:pk>: 捕获整数class型 主键值, 传递给视graph.name: URL模式 名称, 用于 in 模板in反向生成URL.
projectURLconfiguration
然 after in project urls.pyfileinpackage含application URLconfiguration:
# mysite/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')), # package含blogapplication URLconfiguration
]
现 in 可以访问以 under URL:
- http://127.0.0.1:8000/blog/: 显示所 has 博客文章
- http://127.0.0.1:8000/blog/post/1/: 显示ID for 1 博客文章
- http://127.0.0.1:8000/blog/hello/: 显示Hello Worldmessage
提示
usingURL名称而不 is 硬编码URL is a good 习惯, 这样当URLpath变化时, 只需要modifyURLconfiguration, 而不需要modify模板in 所 has 链接.
Django模板system
Django模板system用于生成HTML页面, It supportsvariable, filter器, tag, 模板inheritanceetc.functions.
模板Table of Contents
首先需要 in applicationTable of Contents under creationtemplatesTable of Contents, 并 in 其increationapplication名称 子Table of Contents:
blog/
├── templates/
│ └── blog/
│ ├── post_list.html
│ └── post_detail.html
然 after in settings.pyin确保模板Table of Contents已configuration:
# settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True, # 启用applicationTable of Contents under 模板find
'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',
],
},
},
]
模板语法
Django模板using双 big 括号{{ }}来表示variable, using big 括号加百分号{% %}来表示tag.
variable
<h1>{{ post.title }}</h1>
<p>{{ post.content }}</p>
<p>release日期: {{ post.pub_date }}</p>
filter器
filter器用于modifyvariable 值, using竖线|分隔variable and filter器.
<!-- format日期 -->
<p>release日期: {{ post.pub_date|date:"Y-m-d" }}</p>
<!-- 截取string -->
<p>{{ post.content|truncatechars:100 }}</p>
<!-- 转换 for big 写 -->
<p>{{ post.title|upper }}</p>
tag
tag用于控制模板 逻辑流程, such as条件判断, 循环etc..
条件判断
{% if post.is_published %}
<p>这篇文章已release</p>
{% else %}
<p>这篇文章未release</p>
{% endif %}
循环
{% for post in posts %}
<h2><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2>
<p>{{ post.content|truncatechars:100 }}</p>
<p>release日期: {{ post.pub_date|date:"Y-m-d" }}</p>
{% endfor %}
URL反向解析
<a href="{% url 'post_detail' pk=post.pk %}">查看详情</a>
<a href="{% url 'post_list' %}">返回list</a>
模板inheritance
模板inheritance允许creation一个Basics模板, 然 after in other模板ininheritance并scale它, implementationcode复用.
Basics模板 (base.html)
<!-- blog/templates/blog/base.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Blog{% endblock %}</title>
</head>
<body>
<header>
<h1><a href="{% url 'post_list' %}">My Blog</a></h1>
</header>
<main>
{% block content %}
{% endblock %}
</main>
<footer>
<p>© 2023 My Blog</p>
</footer>
</body>
</html>
子模板 (post_list.html)
<!-- blog/templates/blog/post_list.html -->
{% extends 'blog/base.html' %}
{% block title %}博客list{% endblock %}
{% block content %}
{% for post in posts %}
<article>
<h2><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2>
<p>{{ post.content|truncatechars:100 }}</p>
<p>release日期: {{ post.pub_date|date:"Y-m-d" }}</p>
</article>
{% endfor %}
{% endblock %}
子模板 (post_detail.html)
<!-- blog/templates/blog/post_detail.html -->
{% extends 'blog/base.html' %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<article>
<h1>{{ post.title }}</h1>
<p>{{ post.content }}</p>
<p>release日期: {{ post.pub_date|date:"Y-m-d H:i:s" }}</p>
{% if post.is_published %}
<p>status: 已release</p>
{% else %}
<p>status: 未release</p>
{% endif %}
</article>
<a href="{% url 'post_list' %}">返回list</a>
{% endblock %}
静态file
静态fileincludingCSS, JavaScript, graph片etc.. Djangoproviding了静态filemanagementfunctions.
静态fileTable of Contents
in applicationTable of Contents under creationstaticTable of Contents, 并 in 其increationapplication名称 子Table of Contents:
blog/
├── static/
│ └── blog/
│ ├── css/
│ │ └── style.css
│ ├── js/
│ │ └── main.js
│ └── images/
│ └── logo.png
in 模板inusing静态file
首先需要 in 模板in加载statictag, 然 after usingstatictag引用静态file:
<!-- in 模板顶部加载statictag -->
{% load static %}
<!-- 引用CSSfile -->
<link rel="stylesheet" href="{% static 'blog/css/style.css' %}">
<!-- 引用JavaScriptfile -->
<script src="{% static 'blog/js/main.js' %}"></script>
<!-- 引用graph片 -->
<img src="{% static 'blog/images/logo.png' %}" alt="Logo">
练习 1: creation视graph and 模板
- in blogapplicationincreation一个 simple function视graph, 返回"Hello Blog".
- in URLconfigurationin添加相应 routing.
- creation一个using模板 视graph, 显示所 has 博客文章.
- creationBasics模板 and 文章list模板.
- in 模板inusing静态file.
练习 2: usingclass视graph
- 将function视graphreplace for ListView and DetailViewclass视graph.
- testclass视graph functions.
- 添加一个CreateViewclass视graph, 用于creation new 博客文章.