Django学习路4_数据库添加元素,读取及显示到网页上

在 views 中实现对数据库的添加和读取数据库

添加数据

对象 = models 中创建的类名()
对象.列名 = '字段值' 
对象.save() 进行保存
return HttpResponse('提示信息')
def add_student(request):
    stu = Student()
    stu.s_name = 'Hany_%d'%(random.randrange(10))
    stu.save()
    return HttpResponse("添加成功,添加的姓名为 %s"%(stu.s_name))
在 urls 中的 urlpatterns 中进行注册

url(r'addstu',views.add_student),

读取数据

对象 = models 中的类名.objects.all()
来获取objects 的接口

创建 context (字典对象)传递给 templates 中的 html 文档
context 的键是html 中需要使用的,值是需要显示的
context 是 from django.shortcuts import render 函数的参数
context = {
  '键':值,
  '键2':值2
}

def get_student(request):

    stus = Student.objects.all()
    # 获取所有学生,objects 操作的入口
    context = {
        'hobby':'使用 Python 学 Django !',
        'stus':stus
    }
    # context 是一个字典,用来与 html 代码进行关联
    return render(request,'stu_list.html',context = context)
注:stu_list.html 是在 templates 中创建的 stu_list.html 文档

在 HTML 代码中显示

使用 {{view.py 函数中传递过来的 context 参数的键}} 即可访问
如果需要显示全部的数据,需要进行遍历
for 循环
{{% for 对象 in 键%}}
<标签名>{{对象.表的列名}}</标签名>
{{endfor}}
注:表的列名:models 的类中定义的属性
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>StudentList</title>
</head>
<body>
<h2>学生表</h2>
<h3> {{hobby}}</h3>

<h1>学生名单</h1>
<ul>
    {% for stu in stus %}
    <li>{{ stu.s_name }}</li>
    {% endfor  %}
</ul>
</body>
</html>

 

 

 

 

 

 

 

 


2020-05-07

posted @ 2020-05-07 11:40  CodeYaSuo  阅读(688)  评论(0编辑  收藏  举报