1、为test.DB数据库预先创建下面数据
1 张三 16 2015-01-02 1
2 李四 17 2015-01-04 1
3 王五 14 2015-04-24 0
2、配置C:\djangoweb\helloworld\blog\urls.py文件
# -*- coding: UTF-8 -*- from django.conf.urls import patterns, include, url urlpatterns = patterns(‘blog.views‘, url(r‘^index/$‘, ‘index‘), url(r‘^time/$‘, ‘time‘), url(r‘^shengfen/$‘, ‘shengfen‘), #url(r‘^foo/(\d{4})/$‘, ‘foo‘), #表示接收4个数字,#\w+接收至少一个字母 url(r‘^foo/(\d{4})/(\w+)/$‘,"foo"), url(r‘^bar/(?P<id>\d{4})/(?P<name>\w+)/$‘,‘bar‘),#强制规定bar(request,id,name)处的参数必须为id和name url(r‘^student_list/$‘,‘student_list‘),#当浏览器打开此网址时,输出html页面的结果(html页面定义了从数据库抓取数据的代码) )
3、配置views.PY文件
# Create your views here. #coding:utf-8 from django.http import HttpResponse import datetime #导入templates文件所需导入库 from django.template import loader,Context #引入models模块中的Student等类 from blog.models import * def student_list(request): t=loader.get_template("student_list.html") studentList = Student.objects.all() # 等价于 select * from student c=Context({"studentList":studentList}) return HttpResponse(t.render(c)) class Person(): def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex def myMethod(self): return "get it" def time(request): t = loader.get_template("time.html") myId = request.GET.get("id") myName = request.GET.get("name")#获取传递的name的value值 user = {"today": datetime.datetime.now(),"id":myId,"name":myName} c = Context(user) return HttpResponse(t.render(c)) def foo(request,myID,myName): t = loader.get_template("foo.html") user = {"today": datetime.datetime.now(),"id":myID,"name":myName} c = Context(user) return HttpResponse(t.render(c)) def bar(request,id,name): t = loader.get_template("bar.html") user = {"today": datetime.datetime.now(),"id":id,"name":name} c = Context(user) return HttpResponse(t.render(c)) def shengfen(request): t = loader.get_template("shengfen.html") user = {"shengfen":"湖北省恩施市"} c = Context(user) return HttpResponse(t.render(c)) def index(request): #加载器,加载模板 t=loader.get_template("index.html") # django之创建第4-1个项目-Dict形式 user = {"name": "xiaodeng", "sex": "male", "age": 28,"today":datetime.datetime.now()} c = Context({"test": user}) # 在这里test位变量,user为变量的值 return HttpResponse(t.render(c))
4、创建student_list.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <li>遍历数据库student中的数据</li> {% for student in studentList %} <li>{{student}}</li> <!--Student objec--> {% endfor %} <br> {% for student in studentList %} <li>{{student.name}},{{student.age}}</li> {% endfor %} </body> </html>
5、启动服务器,manage.py runserver
6、打开 http://127.0.0.1:8000/blog/student_list/
7、百度云盘:django之创建第8-1个项目-数据库之增删改查/数据库数据显示在html页面
时间: 2024-10-13 19:32:33