Django模板导入和替换、以及对数据库的增加、查看

静态文件引入的3中方式:例如对html模板里面对css样式的引入

STATIC_URL = '/static666/'
STATICFILES_DIR=[
os.path.join(BASE_DIR,'static')
]

目的是在settings里面名字变动时,模板里面能时时进行检测和变动,从而不影响页面css样式的加载

<head>
    <meta charset="UTF-8">
    <title>模板的导入和继承</title>
    <!--方式一:-->
{#    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">#}

    <!--方式二:就是settings里面STATIC_URL = '/static666/'后面的值无论如何变动都不会有影响,对应css样式的加载,都能识别到STATIC_URL地址的变动-->
    {% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css'%}">
{#    返回值:/atic/bootstrap-3.3.7-dist/css/bootstrap.min.css#}

    <!--方式三:-->
     <link rel="stylesheet" href="{% get_static_prefix %}/bootstrap-3.3.7-dist/css/bootstrap.min.css">
{#    返回值:/static#}

    <style>

    </style>
</head>

 图解说明:

模板的导入:

模板导入:
  1 把公共部分,放到html里,比如叫 left.html
  2 想在哪里用 {% include 'left.html' %}

正常情况下模板里面直接写html语句

要实现的就是,将html中一段代码单独放在一个html文件中,其他地方使用的时候去导入就OK:

<div class="panel panel-danger">
                <div class="panel-body">
                    Panel content
                </div>
                <div class="panel-footer">Panel footer</div>
            </div>

            <div class="panel panel-success">
                <div class="panel-body">
                    Panel content
                </div>
                <div class="panel-footer">Panel footer</div>
            </div>

            <div class="panel panel-primary">
                <div class="panel-body">
                    Panel content
                </div>
                <div class="panel-footer">Panel footer</div>
            </div>
left.html单独抽出来作为引用部分
<div class="container-fluid">
    <div class="row">
        <div class="col-md-3">
            #页面里面直接去调用(在哪个位置调用,就在哪个位置显示)
            {% include 'left.html' %}

        </div>
</div>    

模板的继承:

页面切换,母版是固定不动的,所以一些固定不变的可以让他继承不变,相当与空白的盒子,让后面要用的继承这个盒子,再写内容

继承不步骤:
母版继承:
		1  写一个母版 base.html
		2 要更改的地方(    )
		{% block base %}
			母版的盒子里也可以写东西
		{% endblock %}
		3 调用:
			3.1 写在第一行 {%extends 'base.html' %}
			3.2 		{% block base %}
			
						自己的东西
						
						{% endblock my_head%}
			3.3 还想用母版里的内容({{block.super}} 放在那,原来母版里的东西,就会渲染在哪)
					{% block base %}
						{{block.super}}
						自己的东西						
					{% endblock my_head%}
			3.4 如过不继承盒子,它会用原来的内容,如果继承了,没写自己的东西,它会空白
			3.5 盒子再继承时,跟顺序无关

例如下面:

首先,定义一个母模板base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>母模板样式</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
    <style>
        .head {
            height: 100px;
            width: 100%;
            background-color: deepskyblue;
        }

    </style>
</head>
<body>

<div class="head"></div>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-3">
            {% block base_left %}
                母模板原col-md-3左侧内容
            {% endblock %}
        </div>

        <div class="col-md-9">
            {% block base_right %}
                母模板原col-md-9右侧内容
            {% endblock base_right %}
        </div>

    </div>

</div>

</body>
</html>

其次,定义一个子模板order.html,并配置

<!--先导入父模板-->
{% extends 'base.html' %}
<!--指定重写继父模板固定那哪一块儿内容,重新写自己的新内容-->
{% block base_left %}
    <!--默认会覆盖掉父模板对应位置的内容,如果要保留原有内容可以写block.super-->
    {{ block.super }}
    <hr>
    <!--本页面新增内容-->
    继承过来的左侧新页面,自己的新内容
{% endblock  %}


<!--结束时候另外一种写法,endblock后面可以指定结束的的盒子名称(也可以不写)-->
{% block base_right %}
    {{ block.super }}
    <hr>
    继承过来的右侧新页面,自己的新内容
{% endblock base_right%}

最后,实现子模板继承母模板的样式,并且在继承的基础上可以重写自己页面的新内容

数据库的增加:

models.py里面的先配置数据库表的字段及类型

from django.db import models

# Create your models here.
from django.db import models
class Book(models.Model):
    nid=models.AutoField(primary_key=True)
    name=models.CharField(max_length=40)
    price=models.DecimalField(max_digits=5,decimal_places=2)
    pub_date=models.DateField()
    author=models.CharField(max_length=40)
    publish=models.CharField(max_length=60)

views.py函数里面对数据的增加操作

from django.shortcuts import render

# Create your views here.
from app01.models import *

def index(request):
    #数据库增加
    #方法1:(推荐使用第一种方式)

    Book.objects.create(name='书4',price=56,pub_date='1992-10-12',author='作者1',publish='人民出版社')
    import datetime #传字符串必须是:2014-09-18,也可以传datetime类型
    now = datetime.datetime.now()
    Book.objects.create(name='书9',price=25.4,pub_date=now,author='作者9',publish='中央出版社99')
    book=Book.objects.all().values('name','price') #<QuerySet [{'name': '书1', 'price': Decimal('23.40')}, {'name': '书1', 'price': Decimal('23.40')},
    print(book)



    #方法2:(最后记得要保存)
    book=Book(name='书3',price=30,pub_date='2001-01-12',author='作者3',publish='上海出版社')
    print(book,type(book))
    book.save()

     return render(request,'index.html')

数据库的查询:

views.py对数据库的查询操作

# Create your views here.
from app01.models import *

def index(request):

    #数据查看
    #方法1:filter
    filter(queryset对象)相当于sql的where后面传的参数,是and的关系
    books=Book.objects.filter(publish='中央出版社',)
    print(books) #<QuerySet [<Book: Book object>, <Book: Book object>, <Book: Book object>]> 查看的是所有满足条件的列表

    print(books.first())  #Book object 取出列表中第一个,就对行啊
    print(books[0])  #Book object同上面一样

    print(books.first().nid) # 1
    print(books[0].nid) #同上面一样


    #方法2:get后面条件参数,必须是数据库里面是唯一的一个,不然会报错
    book = Book.objects.get(name='书1') #例如:这种就会报错
    book=Book.objects.get(nid=4)
    print(type(book))  #<class 'app01.models.Book'>
    print(book.name)


    #方法3:
    #拿所有的 - -queryset对象
    book=Book.objects.all()
     # first() 从queryset里取出第一个值---->book对象
    book=Book.objects.all().first()
    print(book) #Book object
    print(book.nid) #1
    print(book)# #[<Book: Book object>, <Book: Book object>,..
    book = Book.objects.all().values('name','price')
    print(book)  #<QuerySet [{'name': '书1', 'price': Decimal('23.40')}, ..
    # 一旦返回是queryset对象,可以继续点它的方法
    book = Book.objects.all().values('name', 'price').filter(name='书1')
    print(book)

    #exclude查找排除谁之外的所有结果
    book=Book.objects.all().exclude(author='作者1')
    print(book.first().nid) #3


    #order_by默认是从小到大,想要从打到小-
    book = Book.objects.all().order_by('price')
    book=Book.objects.all().order_by('-price')
    print(book.first().name)

    # count 计算有多少条数据信息
    book=Book.objects.all().count()
    print(book) #29
    book=Book.objects.all().last()
    print(book.name)

    #exists判断queryset里有没有数据,没有就false,有就是true
    res=Book.objects.all().exists()
    print(res)  #true

    #values_list:是元祖的形式
    book=Book.objects.all().values_list('name','price') #结果[(),()]里面是元祖
    print(book.order_by('price'))

    #distinct去重
    #去重前查询结果
    book=Book.objects.values('publish') #<QuerySet [{'publish': '中央出版社'}, {'publish': '中央出版社'}, {'publish': '上海出版社'},
    #去重后查询结果
    book=Book.objects.values('publish').distinct() #<QuerySet [{'publish': '中央出版社'}, {'publish': '上海出版社'}, {'publish': '人民出版社'},
    print(book)

    #reverse反转要放到order_by后面
    book=Book.objects.all().order_by('-price','pub_date').values_list().reverse()
    print(book)

    return render(request,'index.html')
原文地址:https://www.cnblogs.com/yangzhizong/p/9613285.html