前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Django 之模板篇

Django 之模板篇

原创
作者头像
ruochen
修改2021-05-13 14:32:44
6310
修改2021-05-13 14:32:44
举报
文章被收录于专栏:若尘的技术专栏

<font color="red">欢迎阅读本专栏其他文章</font>

Django 之路由篇

Django 之视图篇

Django 之 Models(Models 模型 & 数据表关系)

模板系统

用到的代码会放在文末

  • 模板:一组相同或者相似的页面,在需要个性化的地方进行留白,需要的时候只是用数据填充就可以使用
  • 步骤:
    1. 在settings中进行设置: TEMPLATES
    2. 在templates文件夹下编写模板并调用

模板-变量

  • 变量的表示方法;{{var_name}}
  • 在系统调用模板的时候,会用相应的数据查找相应的变量名称,如果能找到,则填充,或者叫渲染,否则,跳过
  • 案例 two.html
代码语言:txt
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>案例二</title>
</head>
<body>

<h1 style="color: red">Hello {{name}}</h1>
<h1 style="color: blue">Hello {{name2}}</h1>
</body>
</html>

模板-标签

  • for标签: {% for .. in .. %}
  • 用法:
代码语言:txt
复制
    {% for .. in .. %}
代码语言:txt
复制
        循环语句
代码语言:txt
复制
    {% endfor %}
  • 案例 three.html,显示班级成绩<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>案例三</title> </head> <body> {% for s in score %} <h1 style="color: deeppink">{{s}}</h1> {% endfor %} </body> </html>

if 标签

  • 用来判断条件
  • 代码示例:
代码语言:txt
复制
    {& if 条件 &}
代码语言:txt
复制
        条件成立执行语句
代码语言:txt
复制
    {% elif 条件 %}
代码语言:txt
复制
        条件成立执行语句
代码语言:txt
复制
    {% else %}
代码语言:txt
复制
        以上条件都不成立执行语句
代码语言:txt
复制
    {% endif %}
  • 案例 four.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>案例四</title> </head> <body> {% if name == "ruochen" %} <h1> {{name}}, 你好, </h1> {% elif name == "ruo" %} <h1> {{name}}, 你还记得大明湖畔的下雨天的荷吗? </h1> {% else %} <h1> {{name}}, 你还有遗憾吗? </h1> {% endif %} </body> </html>csrf 标签<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>案例五</title> </head> <body> <form action="/five_post/" method="post"> {% csrf_token %} 用户名: <input type="text" placeholder="请输入用户名" name="username"> <br> 密码: <input type="password" name="password"> <br> <input type="submit" value="提交"> </form> </body> </html>
  • csrf:跨站请求伪造
  • 在提交表单的时候,表单页面需要加上 {% csrf_token %}
  • 案例five_get, five_post

源码

  • urls.py
代码语言:txt
复制
from django.conf.urls import include, url
from django.contrib import admin
from mytpl import views as v

urlpatterns = [
    # Examples:
    # url(r'^$', 'django_tpl.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^one/', v.one),
    url(r'^two/', v.two),
    url(r'^three/', v.three),
    url(r'^four/', v.four),
    url(r'^five_get/', v.five_get),
    url(r'^five_post/', v.five_post),

]
  • views.py
代码语言:txt
复制
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def one(request):
    return render(request, r'one.html')

def two(request):
    # 用来存放模板中传递的数据
    ct = dict()
    ct['name'] = 'ruochen'
    ct['name2'] = 'ruo'
    return render(request, r'two.html', context=ct)

def three(request):
    ct = dict()
    ct['score'] = [99, 86, 23, 100, 46]
    return render(request, r'three.html', context=ct)

def four(request):
    ct = dict()
    ct['name'] = 'ru'

    return render(request, r'four.html', context=ct)

def five_get(request):
    return render(request, r'five_get.html')

def five_post(request):
    print(request.POST)
    return render(request, r'one.html')
  • settings.py
代码语言:txt
复制
"""
Django settings for django_tpl project.

Generated by 'django-admin startproject' using Django 1.8.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_qwgzdbkb&m5tzm%@b*^xh7(!u-)-v&&uk896dxj)wj3^@h_xb'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'mytpl',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'django_tpl.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 告诉django,在当前项目目录下查询叫templates的文件夹,下面是模板
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'django_tpl.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 模板系统
    • 模板-变量
      • 模板-标签
        • if 标签
          • 源码
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档