模板、过滤器、模板继承以及思路

创建模板

1、新建一个templates文件夹 --- 用来存放html

2、在站点中的settings的TEMPLATES中进行以下设置指定templates目录地址,

和工程目录同级

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 设置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',
            ],
        },
    },
]

3、在templates下创建html文件

4、使用:在应用的views中设置函数,将html文件渲染到页面,将想要显示的对象也引入

在views中方法返回/页面
data = {
    'stus':stus
}
render(request,'压面',data)

def index(request):
    if request.method == 'GET':
        stus = Student.objects.all()
        return render(request,'index.html',{'stus':stus})

5、在html中进行编辑

在html中使用for、if、while等需要注意格式问题,使用完函数需要加{% end函数名 %}
例子:
{% for stu in stus %}
    ID:{{ stu.id }}
    年龄:{{ stu.s_sge }}
{% endfor %}

{% if 表达式 %}
语句1
{% else %}
语句2
{% endif %}
例子
{% if stu.s_sex %}
    性别:男
{% else %}
    性别:女
{% endif %}

页面放在templates文件夹中,静态的文件(css、js等)放在static中

for循环,
if 
ifequal --- 如果相等
forloop.counter --- 循环计数,从1开始依次加1
forloop.counter0 --- 循环计数,从0开始
forloop.revcounter0 --- 循环计数,倒序到0
forloop.frist --- 如果是第一个则是Ture
forloop.last --- 如果是最后一个则是Falase
{% for xx in xxx %}

{% endfor %}

{% if xxx==1 %}

{% endif %}

if的另一个写法

{% ifequal forloop.counter0 1 %}
    <span style="font-weight:bold;">年龄:{{stu.s_age }}</span>
{% else %}
    <span>年龄:{{ stu.s_age }}</span>
{% endifequal %}

编号

{{ forloop.counter }} ---循环一次值加一,默认是1,counter0为从0开始 revcounter -- 倒序
<!-- forloop循环调用  counter计数器-->
编号: {{ forloop.counter0 }}
{% if forloop.counter0 == 1 %}
    <span style="color:red"> 学生:{{ stu.s_name}}</span>
{% else %}
    <span style="color:yellow"> 学生:{{ stu.s_name}}</span>
{% endif %}

static文件夹(css、js、和images)

1、创建一个static文件夹,因为站点中的settings.py有:
STATIC_URL = '/static/'---如果文件名为其他名字,这里相应的进行修改就行了
在html文件中可以通过{% load static from staticfiles %}进行使用路径,例如:
    <img src="{% static 'myApp/img/2.png' %}"/> --- 这里的static就是STATIC_URL的static,运用它可以方便路径发生改变时进行修改
2、设置static的路径
STATIC_URL = '/static/' --- 普通文件路径(例如图片),如果只是图片路径可以不写下面的代码

STATICFILES_DIRS = [   ---  CSS和JS等需要使用此路径
    os.path.join(BASE_DIR, 'static')

]


静态css、js、imgage样式的引入

在html中引入css、js、images
第一种:
<link rel="stylesheet" href="/static/css/index.css" >

第二种:
<!-- load装载 -->
{% load static  %}
<link href="{% static 'css/index.css' %}" rel="stylesheet">
最好使用第二种

js和imgage的引入也是一样

注释

<!-- 不能写成大括号中包含两个百分号的格式,会注解-->
<!-- {% %} -->
 
<!-- 单行注释 --> ---- 这个注释会在后台代码中显示
    {# 注释 #} --- 不会再后台中显示
<!-- 多行注释 -->
{% comment %}

{% endcomment%}

请求

request

http:get请求
    request.GET.get()
    
http:post请求
    request.POST.get()

判断请求:    
request.method ==> GET,POST

render方法解释

此方法的作用---结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 HttpResponse 对象。

解析

def index(request):
    if request.method == 'GET':
        stus = Student.objects.all()
        # 其中{'stus':stus}的values的值是学生所有的对象,键就是在页面解析的参数的值
        return render(request,'index.html',{'stus':stus})
        
在html页面通过{{ stus }} --- 将参数进行解析,获得Queryset对象
例子:
    for循环用于解析数据,在页面中进行展示
    {% for stu in stus %}
        姓名:{{ stu.s_name }}
        年龄:{{ stu.s_age }}
        {% if stu.s_sex %}
            性别:男
        {% else %}
            性别:女
        {% endif %}
        <br/>
    {% endfor %}
在页面显示学生对象的姓名和年龄

注意all()的使用

在html中获得Queryset不在是all(),而是all
{% for course in stu.course_set.all %}
    课程:{{ course.c_name }}
{% endfor %}

过滤器

格式:{{ 对象.字段 | 过滤器:值 }}
add:数值
add:10 --- 加10     add:-10 --- 减10
语文成绩:{{stu.language_score | add:10 }}

date:'y-m-d h-m-s'--- 时间转换,如果时间是英文显示的,可以加过滤器date变为中文显示
创建时间:{{stu.create_time | date:'y-m-d h:m:s'}}

upper --- 大写  lower --- 小写
姓名:{{stu.s_name | upper | lower}} --- 多个过滤器可以一起写,采用最后一个过滤器

为了安全起见和防止页面是乱码,django提供了safe 过滤器,主要是一些特殊字符、空格、换行等
为了想要在页面显示正常,需要在数据后添加safe过滤器

 {{ context | safe}} 

显示关联表的信息

<!-- 根据学生找到班级名称 -->
    班级:{{stu.g.g_name}}  --- g是在学生中关联的外键关系名
<!-- 找到学生的课程 -->
    {% for course in stu.course_set.all %}
        课程:{{ course.c_name }}
    {% endfor %}

思路

1、先确定要完成的功能,在urls中定义路由
     # 返回页面,学生信息
     url(r'selStuen',views.selStuen,name='sel_stu'),
2、在views中建立方法
    def selStuen(request):
    if request.method == 'GET':
        return render(request, 'students.html')
    返回student.html页面
3、将要渲染的的对象,包装进入student.html页面
    def selStuen(request):
    if request.method == 'GET':
        stus = Student.objects.all()
        return render(request, 'students.html',
                      {'stus': stus})
4、在html中写循环(可以使用表格进行布局)
    <table align=center>
    <tr >
        <th >ID</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>班级</th>
        <th>操作</th>
    </tr>
    {% for stu in stus %}
    <tr>
        <td>{{stu.id}}</td>
        <td>{{stu.s_name}}</td>
        <td>{{stu.s_age}}</td>
        <td>{{stu.g.g_name}}</td>
        <td>
            <a href="">删除</a>

            <a href="">编辑</a>

            <!--<a href="/app/addStuCourse/{{ stu.id }}">添加课程</a>-->
        </td>
    </tr>
    {% endfor %}
</table>

5、实现删除功能
    定义路由
    # 删除
    url(r'deleteStu',views.deleteStu),
    建立方法
    def deleteStu(request):
    if request.method == 'GET':
        stu_id = request.GET.get('stu_id')
        stu = Student.objects.get(id=int(stu_id))
        stu.delete()

        # return HttpResponse('删除成功')
        # return HttpResponseRedirect('/app/selStuen')
        # 最好用下面的代码,不要使用路径
        return HttpResponseRedirect(reverse('myapp:sel_stu'))
思考:当点击删除时,我们应该获得想要删除的数据的id值

1、在?后传的值传进deleteStu中 ---  <a href="/app/deleteStu/?stu_id={{ stu.id }}">删除</a>
 <a href="{% url 'backweb:index' %}?page={{ i }}">{{ i }}</a> --- 另一种写法的传参

?后面的长度:协议并没有限制长度,但是不同的浏览器对齐有不同的限制
后端将接受deleteStu方法

2、<a href="/app/addStuCourse/{{ stu.id }}">添加课程</a> --- 
    设置路由: url(r'addStuCourse/(\d+)', views.addStuCourse) --- (\d+)接收动态的id
    
3、在方法中添加参数,接收获取的动态id
def addStuCourse(request, id):
    if request.method == 'GET':
        # stu = Student.objects.get(id=id)
        courses = Course.objects.all()
        return render(request, 'courses.html',
                      {'courses': courses})
    if request.method == 'POST':
        stu = Student.objects.get(id=id)
        c_id = request.POST.get('c_id')
        c = Course.objects.get(id=c_id)
        stu.course_set.add(c)
        return HttpResponseRedirect('/app/selStuen/')

注意a标签的href问题

 <a href="/sunck/quit">退出登陆</a> --- 跳转到相应的页面
 
 <a href="sunck/quit">退出登陆</a> --- 在当前的页面后添加href路径
  也可以向下面一样写:和第一个类似
 <a href="{% url 'backweb:index' %}" class="active">文章列表</a>

模板继承

挖坑、填坑
一般是创建一个base.html页面,用来挖坑,创建一个base_main.html用来填页面共同拥有的坑,在页面中继承base_main.html

1、在基础模板中挖坑(base.html)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
        {# 挖坑 #}
        {% block title %}
        {% endblock %}
    </title>
    {# 挖坑 #}
    {% block extCss %} --- 同样可以给js挖坑
    {% endblock %}
</head>
<body>
    {# 挖坑 #}
    {% block content %}
    {% endblock %}
</body>
</html>

2、填坑 --- 在页面中继承继承模板
{% extends 'base.html' %}

{% block titel %}
    我是首页
{% endblock %}

{% block extCss %} 
    {{ block.super }} --- 继承基础模板坑中的内容,如果不写继承就会清空基础模板的内容
{% endblock %}

{% extends 'base.html' %}可以看做整个base.html页面,在base.html中挖的坑可以看做是类(base.html)
中的方法,其他页面通过{% extends 'base.html' %}继承了base.html的整个页面

{% 在某个标签中挖的坑,就可以看做这个标签中的父坑 %},其他页面可以通过{{block.super}}继承这个父坑的
内容,并在其后添加内容(类似于类的继承)

注意:如果没有使用{{ blcok.super }}继承,则父坑的内容将不会继承

如果不写坑名则自动继承主坑的内容

如果写了坑名,不写block.super就会清空主坑的内容。

写了坑名并且使用了block.super就会继承主坑的内容

猜你喜欢

转载自blog.csdn.net/weixin_42750983/article/details/81983059