好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Django2:Web项目开发入门笔记(10)

这一篇教程,我们把前面所学的内容做一下巩固练习,并且再接触一些新的知识内容,例如视图向JS返回数据时的处理以及JQuery中循环的使用等等。

先来看看,我们要实现的目标。

一、完成商品列表以及页面内容的呈现。

先不管添加和查询功能,我们先把上方呈现的页面实现出来。

1、创建模型(models.py)

这次我们创建的模型类,以商品名称为主键。

示例代码:

class GoodsInfo(models.Model):
    goods_name = models.CharField(max_length=30, <strong>primary_key=True</strong>)
    goods_number = models.IntegerField()
    goods_price = models.FloatField()

创建好模型类之后,通过“makemigrations”和“migrate”创建数据表,并将数据导入数据库。

提示:《 Django2:Web项目开发入门笔记(8) 》中包含所需的数据内容和导入方法。

2、创建模板(goods_list.py)

在模板文件中我们写入HTML代码。

示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>管理商品</title>
</head>
<body>
<h3>商品列表</h3>
价格查询:<input type="text" style="display:inline-block;width:100px;" id="min_price"> ~
<input type="text" style="display:inline-block;width:100px;" id="max_price">
<button type="button" id="search">确定</button>
<br>
<br>
<div id="list">
    {% for goods in goods_list %}
        <div id="{{ goods.goods_name }}">
            <label style="display:inline-block;width:120px;">名称:{{ goods.goods_name }}</label>
            <label style="display:inline-block;width:90px;">数量:{{ goods.goods_number }}</label>
            <label style="display:inline-block;width:90px;">价格:{{ goods.goods_price }}</label>
            <button class="delete" type="button" id="{{ goods.goods_name }}">删除</button>
            <br>
        </div>
    {% endfor %}
</div>
<br>
名称:<input type="text" style="display:inline-block;width:65px;" id="goods_name">
数量:<input type="text" style="display:inline-block;width:40px;" id="goods_number">
价格:<input type="text" style="display:inline-block;width:40px;" id="goods_price">
<button type="button" id="add">添加</button>
<label id="add_msg"></label>
</body>
</html>

注意,上方代码中每个标签都有“id”属性,这个属性方便我们实现之后添加的功能。

特别是,商品列表中每个删除按钮的“id”,这里使用了每条商品信息中的商品名称做为属性值,实现删除功能时,就可以依据这个“id”属性的值进行删除。

另外,每一条商品信息的多个“label”标签和删除按钮的“button”标签,都写在一对“div”标签中。

查看更多关于Django2:Web项目开发入门笔记(10)的详细内容...

  阅读:16次