Django 之模板篇

淩亂°似流年 2023-02-24 08:13 124阅读 0赞

#

  • 模板系统
    • 模板-变量
    • 模板-标签
    • if 标签
    • csrf 标签
    • 源码

[欢迎阅读本专栏其他文章]
Django 之路由篇
Django 之视图篇
Django 之 Models(Models 模型 & 数据表关系)

模板系统

用到的代码会放在文末

  • 模板:一组相同或者相似的页面,在需要个性化的地方进行留白,需要的时候只是用数据填充就可以使用
  • 步骤:

    1. 在settings中进行设置: TEMPLATES
    2. 在templates文件夹下编写模板并调用

模板-变量

  • 变量的表示方法;{ {var_name}}
  • 在系统调用模板的时候,会用相应的数据查找相应的变量名称,如果能找到,则填充,或者叫渲染,否则,跳过
  • 案例 two.html

    <!DOCTYPE html>




    案例二



    Hello {
    {name}}


    Hello {
    {name2}}



模板-标签

  • for标签: {% for … in … %}
  • 用法:

    1. {% for .. in .. %}
    2. 循环语句
    3. {% endfor %}
  • 案例 three.html,显示班级成绩

    <!DOCTYPE html>




    案例三



    {% for s in score %}

    {
    {s}}



    {% endfor %}


if 标签

  • 用来判断条件
  • 代码示例:

    1. {& if 条件 &}
    2. 条件成立执行语句
    3. {% elif 条件 %}
    4. 条件成立执行语句
    5. {% else %}
    6. 以上条件都不成立执行语句
    7. {% endif %}
  • 案例 four.html

    <!DOCTYPE html>




    案例四



    {% if name == “ruochen” %}


    {
    {name}}, 你好,


    {% elif name == “ruo” %}


    {
    {name}}, 你还记得大明湖畔的下雨天的荷吗?


    {% else %}


    {
    {name}}, 你还有遗憾吗?


    {% endif %}

csrf 标签

  • csrf:跨站请求伪造
  • 在提交表单的时候,表单页面需要加上 {% csrf_token %}
  • 案例five_get, five_post

    <!DOCTYPE html>




    案例五




    {% csrf_token %}
    用户名:


    密码:






源码

  • urls.py

    from django.conf.urls import include, url
    from django.contrib import admin
    from mytpl import views as v

    urlpatterns = [

    1. # Examples:
    2. # url(r'^$', 'django_tpl.views.home', name='home'),
    3. # url(r'^blog/', include('blog.urls')),
    4. url(r'^admin/', include(admin.site.urls)),
    5. url(r'^one/', v.one),
    6. url(r'^two/', v.two),
    7. url(r'^three/', v.three),
    8. url(r'^four/', v.four),
    9. url(r'^five_get/', v.five_get),
    10. url(r'^five_post/', v.five_post),

    ]

  • views.py

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

    Create your views here.

    def one(request):

    1. return render(request, r'one.html')

    def two(request):

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

    def three(request):

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

    def four(request):

    1. ct = dict()
    2. ct['name'] = 'ru'
    3. return render(request, r'four.html', context=ct)

    def five_get(request):

    1. return render(request, r'five_get.html')

    def five_post(request):

    1. print(request.POST)
    2. return render(request, r'one.html')
  • settings.py

    “”” 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

    BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(_file)))

  1. # Quick-start development settings - unsuitable for production
  2. # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
  3. # SECURITY WARNING: keep the secret key used in production secret!
  4. SECRET_KEY = '_qwgzdbkb&m5tzm%@b*^xh7(!u-)-v&&uk896dxj)wj3^@h_xb'
  5. # SECURITY WARNING: don't run with debug turned on in production!
  6. DEBUG = True
  7. ALLOWED_HOSTS = []
  8. # Application definition
  9. INSTALLED_APPS = (
  10. 'django.contrib.admin',
  11. 'django.contrib.auth',
  12. 'django.contrib.contenttypes',
  13. 'django.contrib.sessions',
  14. 'django.contrib.messages',
  15. 'django.contrib.staticfiles',
  16. 'mytpl',
  17. )
  18. MIDDLEWARE_CLASSES = (
  19. 'django.contrib.sessions.middleware.SessionMiddleware',
  20. 'django.middleware.common.CommonMiddleware',
  21. 'django.middleware.csrf.CsrfViewMiddleware',
  22. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  23. 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
  24. 'django.contrib.messages.middleware.MessageMiddleware',
  25. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  26. 'django.middleware.security.SecurityMiddleware',
  27. )
  28. ROOT_URLCONF = 'django_tpl.urls'
  29. TEMPLATES = [
  30. {
  31. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  32. # 告诉django,在当前项目目录下查询叫templates的文件夹,下面是模板
  33. 'DIRS': [os.path.join(BASE_DIR, 'templates')],
  34. 'APP_DIRS': True,
  35. 'OPTIONS': {
  36. 'context_processors': [
  37. 'django.template.context_processors.debug',
  38. 'django.template.context_processors.request',
  39. 'django.contrib.auth.context_processors.auth',
  40. 'django.contrib.messages.context_processors.messages',
  41. ],
  42. },
  43. },
  44. ]
  45. WSGI_APPLICATION = 'django_tpl.wsgi.application'
  46. # Database
  47. # https://docs.djangoproject.com/en/1.8/ref/settings/#databases
  48. DATABASES = {
  49. 'default': {
  50. 'ENGINE': 'django.db.backends.sqlite3',
  51. 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
  52. }
  53. }
  54. # Internationalization
  55. # https://docs.djangoproject.com/en/1.8/topics/i18n/
  56. LANGUAGE_CODE = 'en-us'
  57. TIME_ZONE = 'UTC'
  58. USE_I18N = True
  59. USE_L10N = True
  60. USE_TZ = True
  61. # Static files (CSS, JavaScript, Images)
  62. # https://docs.djangoproject.com/en/1.8/howto/static-files/
  63. STATIC_URL = '/static/'

发表评论

表情:
评论列表 (有 0 条评论,124人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Django 入门模板

    在Django中,将前端的内容定义在模板中,然后再把模板交给视图调用,各种漂亮、炫酷的效果就出现了。 问题 如何向请求者返回一个漂亮的页面呢? 肯定需要用到html、