Django 模板(day4)
在project下创建templates,在templates下创建对应应用的模板目录:
project
├── django.db.models.deletion
├── manage.py
├── project
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-35.pyc
│ │ ├── settings.cpython-35.pyc
│ │ ├── urls.cpython-35.pyc
│ │ └── wsgi.cpython-35.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── templates
│ └── workapp
└── workapp
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│ ├── 0001_initial.py
│ ├── __init__.py
│ └── __pycache__
│ ├── 0001_initial.cpython-35.pyc
│ └── __init__.cpython-35.pyc
├── models.py
├── __pycache__
│ ├── admin.cpython-35.pyc
│ ├── __init__.cpython-35.pyc
│ ├── models.cpython-35.pyc
│ ├── urls.cpython-35.pyc
│ └── views.cpython-35.pyc
├── tests.py
├── urls.py
└── views.py
视图工作原理:http://127.0.0.1.8000/grades当输入网址时,会调用project.urls,继续调用workapp下的urls,接着对应一个视图
在视图里先去models里取数据,然后将数据传输给模板,模板将数据渲染后返回浏览器
总结: 即写模板,定义视图,配置url
模板目录添加路径:/project/settings
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,"templates")], 'APP_DIRS': True,
创建grades,students 模板
模板语法:{{输出值.属性}}
{%代码%}
http://127.0.0.1.8000/grades 写templates
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>班级信息</title> </head> <body> <h1>班级信息列表</h1> <ul> <!--[python1,python2,python3]--> {% for grade in grades %} <li> <a herf="#">{{ grade.gname }}</a> </li> {% endfor %} </ul> </body> </html>
定义视图(一个url对应一个视图)
from django.shortcuts import render from . models import Grades # Create your views here. from django.http import HttpResponse def index(request): return HttpResponse("I love China") def grades(request): # 去models里取数据 gradeslist=Grades.objects.all() # 将数据传输给模板模板在渲染页面,再将渲染好的页面返回浏览器 return render(request,'workapp/grades.html', {"grades":gradeslist})
配置Url
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$',views.index), url(r'^grades/$',views.grades), ]
页面显示:
127.0.0.1:8000/students
配置模板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>学生信息</title> </head> <body> <h1>学生信息列表</h1> <ul> {% for student in students %} <li> {{ student.sname }}--{{ student.scontend }} </li> {% endfor %} </ul> </body> </html>
定义视图
from .models import Students def stu (request): stulist=Students.objects.all() return render(request,'workapp/students.html', {"students":stulist})
配置url
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$',views.index), url(r'^grades/$',views.grades), url(r'^students/$',views.stu), ]
页面显示