建立了数据库后,我们就来做一个简单的表(person_classroom)的加入、删除、改动的操作。

首先我们建立一个加入的页面的模板Classroom_Add.html(加入的表单)并把它放在Bidding\templates\person中:

Classroom_Add.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>数据库操作简单表的加入</title>
</head>
<body>
<h1>这里是Classroom的加入页面</h1>
{% if error %}
<p style="color: red;">请输入班级名称和导师姓名</p>
{% endif %}
<form action="" method="get">
<table border="1" cellpadding="10">
<tr>
<td align="center">项目</td>
<td align="center">内容</td>
</tr>
<tr>
<td align="right">班级名称:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td align="right">导师姓名:</td>
<td><input type="text" name="tutor"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="加入"></td>
</tr>
</table>
</form> </body>
</html>

Classroom_Add_results.html:

<html>
<head>
<title>查询用户结果页</title>
</head>
<body>
<table border="1" cellpadding="5"><tr>
<td>班级:{{name}}加入成功 !</td></tr>
<tr>
<td><a href="http://127.0.0.1:8000/ClassRoom/add/">点击返回</a></td>
</tr>
</table>
</body>
</html>

上面的 这个文件时加入后的结果页。

然后建立相应的view,我们改动person/views.py 文件

Views.py:

# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.db import connection,transaction
from person.models import * def ClassroonAdd(request):
if 'name' in request.GET and request.GET['name'] and 'tutor' in request.GET and request.GET['tutor']:
name = request.GET['name']
tutor = request.GET['tutor'] cursor=connection.cursor()
sql='insert into person_classroom (name,tutor) values (\''+name+'\',\''+tutor+'\')'
cursor.execute(sql)
transaction.commit_unless_managed()
cursor.close() return render_to_response('person/Classroom_Add_results.html',
{'name': name})
else:
return render_to_response('person/Classroom_Add.html', {'error': True})

在改动一下urls.py文件:

from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover() urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Bidding.views.home', name='home'),
# url(r'^Bidding/', include('Bidding.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^hello/$', 'Bidding.views.hello'),
url(r'^time/$', 'Bidding.views.current_datetime'),
url(r'^time/plus/(\d{1,2})/$', 'Bidding.views.hours_ahead'),
url(r'^hello_base/$', 'Bidding.views.hello_base'),
url(r'^request_test/$', 'Bidding.views.request_test'),
url(r'^UsersSearch/$', 'Bidding.Users.views.search_form'),
url(r'^search/$', 'Bidding.Users.views.search'),
url(r'^ClassRoom/add/$', 'person.views.ClassroonAdd'),
)

这时我们的加入就做好了,訪问一下classroom/add这个 页面,就能够看到结果了。

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaGVtZW5nMTk4MA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaGVtZW5nMTk4MA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

只是上面我们所说的办法是运行一个原始的sql语句,这个方式事实上并非Django推荐的,我们能够直接使用models操作数据库的方法。改造一下ClassroomAdd这个视图:

def ClassroonAdd(request):
if 'name' in request.GET and request.GET['name'] and 'tutor' in request.GET and request.GET['tutor']:
name = request.GET['name']
tutor = request.GET['tutor']
c = ClassRoom(name=name,tutor=tutor)
c.save() return render_to_response('person/Classroom_Add_results.html',
{'name': name})
else:
return render_to_response('person/Classroom_Add.html', {'error': True})

这个方案即简单,有不用我们非常多sql的语法。而且最重要的是假设更换数据库类型(sqlserver->oracle)。也不会由于受sql语法不一致的影响。

在接下来,我们来做一个列表页,把数据库中的Classroom表的记录以一个表格的形式显示出来。

还是从模板先入手。建立一个Classroom_List.html,放入Bidding\templates\person目录下:

Classroom_List.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>数据库操作简单表的加入</title>
</head>
<body>
<h1>这里是Classroom的管理页面</h1>
<table border="1" cellpadding="10">
<tr>
<td align="center">序号</td>
<td align="center">班级名称</td>
<td align="center">导师姓名</td>
</tr>
{% for myclass in ClassroonList%}
<tr>
<td align="right">{{ myclass.id }}</td>
<td align="right">{{ myclass.name }}</td>
<td align="right">{{ myclass.tutor }}</td>
</tr>
{% endfor %}
</table> </body>
</html>

加入视图:

# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.db import connection,transaction
from person.models import * def ClassroonAdd(request):
if 'name' in request.GET and request.GET['name'] and 'tutor' in request.GET and request.GET['tutor']:
name = request.GET['name']
tutor = request.GET['tutor'] cursor=connection.cursor()
sql='insert into person_classroom (name,tutor) values (\''+name+'\',\''+tutor+'\')'
cursor.execute(sql)
transaction.commit_unless_managed()
cursor.close() return render_to_response('person/Classroom_Add_results.html',
{'name': name})
else:
return render_to_response('person/Classroom_Add.html', {'error': True}) def ClassroonAdd(request):
if 'name' in request.GET and request.GET['name'] and 'tutor' in request.GET and request.GET['tutor']:
name = request.GET['name']
tutor = request.GET['tutor']
c = ClassRoom(name=name,tutor=tutor)
c.save() return render_to_response('person/Classroom_Add_results.html',
{'name': name})
else:
return render_to_response('person/Classroom_Add.html', {'error': True}) def ClassroonList(request):
cursor=connection.cursor()
sql='select id,name,tutor from person_classroom'
ClassroonList=ClassRoom.objects.raw(sql)
return render_to_response('person/Classroom_List.html',
{'ClassroonList': ClassroonList})

配置urls.py:

from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover() urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Bidding.views.home', name='home'),
# url(r'^Bidding/', include('Bidding.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^hello/$', 'Bidding.views.hello'),
url(r'^time/$', 'Bidding.views.current_datetime'),
url(r'^time/plus/(\d{1,2})/$', 'Bidding.views.hours_ahead'),
url(r'^hello_base/$', 'Bidding.views.hello_base'),
url(r'^request_test/$', 'Bidding.views.request_test'),
url(r'^UsersSearch/$', 'Bidding.Users.views.search_form'),
url(r'^search/$', 'Bidding.Users.views.search'),
url(r'^ClassRoom/add/$', 'person.views.ClassroonAdd'),
url(r'^ClassRoom/list/$', 'person.views.ClassroonList'),
)

如同上述讨论的一样,我们如今的视图运行的是一个原始的sql,如今我们须要用models来改动一下:

def ClassroonList(request):
cursor=connection.cursor()
ClassroonList=ClassRoom.objects.all()
#ClassroonList=ClassRoom.objects.filter(name__icontains='大')
return render_to_response('person/Classroom_List.html',
{'ClassroonList': ClassroonList})

假设须要运行where或者order by等操作能够这样:

ClassroonList=ClassRoom.objects.filter(name__icontains='大').order_by(‘name’)

这里还有非常多关于选择的内容以后我们逐渐会介绍到。

做完了列表页,我们在来做一个改动的页面,思路是这种:在列表页中的每一行的后面加入一列“改动”button。点击button后跳转到改动页面。首先以此条记录的主键专递到改动页面,在改动页面中要先读取出数据库中的信息。然后点击确定button以后运行改动操作。

我们首先来改动这个管理页面的模板:

Classroom_List.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>数据库操作简单表的加入</title>
</head>
<body>
<h1>这里是Classroom的管理页面</h1>
<table border="1" cellpadding="10">
<tr>
<td align="center">序号</td>
<td align="center">班级名称</td>
<td align="center">导师姓名</td>
<td align="center">操作</td>
</tr>
{% for myclass in ClassroonList%}
<tr>
<td align="right">{{ myclass.id }}</td>
<td align="right">{{ myclass.name }}</td>
<td align="right">{{ myclass.tutor }}</td>
<td align="right"><input type="button" onClick="Modify({{ myclass.id }})" value="改动"></td>
</tr>
{% endfor %}
</table>
<script language="javascript">
function Modify(id)
{
location.href='../Modify/'+id
} </script>
</body>
</html>

建立一个Classroom_Modify.html模板。把它放在Bidding\templates\person目录下

Classroom_Modify.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>数据库操作简单表的改动</title>
</head>
<body>
<h1>这里是Classroom--{{name}}的改动页面</h1>
{% if error %}
<p style="color: red;">请输入班级名称和导师姓名</p>
{% endif %}
<form action="" method="get">
<table border="1" cellpadding="10">
<tr>
<td align="center">项目</td>
<td align="center">内容</td>
</tr>
<tr>
<td align="right">班级名称:</td>
<td><input type="text" name="name" value="{{name}}"></td>
</tr>
<tr>
<td align="right">导师姓名:</td>
<td><input type="text" name="tutor" value="{{tutor}}"></td>
</tr>
<tr>
<td colspan="2">
<input type="hidden" name="id" value="{{id}}">
<input type="submit" value="改动">
<input type="button" value="返回" onClick="location.href='../../list'">
</td>
</tr>
</table>
</form>
</body>
</html>

Classroom_Modify_results.html:

<html>
<head>
<title>查询用户结果页</title>
</head>
<body>
<table border="1" cellpadding="5"><tr>
<td align="center"> </td>
<td align="center">改动前</td>
<td align="center">改动后</td>
</tr>
<tr>
<td align="right">班级名称:</td>
<td align="right">{{old_name}}</td>
<td align="right">{{new_name}}</td>
</tr>
<tr>
<td align="right">导师姓名:</td>
<td align="right">{{old_tutor}}</td>
<td align="right">{{new_tutor}}</td>
</tr>
<tr>
<td colspan="3" align="center">改动成功!</td>
</tr>
<tr>
<td colspan="3" align="center"><a href="../../list/">点击返回</a></td>
</tr>
</table>
</body>
</html>

加入视图:

def ClassroonModify(request,id1):
cursor=connection.cursor()
sql='select id,name,tutor from person_classroom where id='+id1
ClassroonList=ClassRoom.objects.raw(sql)
old_name = ClassroonList[0].name
old_tutor = ClassroonList[0].tutor
if 'name' in request.GET and request.GET['name'] and 'tutor' in request.GET and request.GET['tutor']:
new_name = request.GET['name']
new_tutor = request.GET['tutor']
cursor=connection.cursor()
sql='update person_classroom set name=\''+new_name+'\',tutor=\''+new_tutor+'\' where id=\''+id1+'\''
cursor.execute(sql)
transaction.commit_unless_managed()
cursor.close()
return render_to_response('person/Classroom_Modify_results.html',
{'old_name': old_name,'old_tutor':old_tutor,'new_name':new_name,'new_tutor':new_tutor})
else:
return render_to_response('person/Classroom_Modify.html', {'error': True,'id':id1,'name':old_name,'tutor':old_tutor})

编辑urls.py。这里面须要注意的是正则的写法,这个之前的章节已经说过了,这里我们能够再复习一遍:

from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover() urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Bidding.views.home', name='home'),
# url(r'^Bidding/', include('Bidding.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^hello/$', 'Bidding.views.hello'),
url(r'^time/$', 'Bidding.views.current_datetime'),
url(r'^time/plus/(\d{1,2})/$', 'Bidding.views.hours_ahead'),
url(r'^hello_base/$', 'Bidding.views.hello_base'),
url(r'^request_test/$', 'Bidding.views.request_test'),
url(r'^UsersSearch/$', 'Bidding.Users.views.search_form'),
url(r'^search/$', 'Bidding.Users.views.search'),
url(r'^ClassRoom/add/$', 'person.views.ClassroonAdd'),
url(r'^ClassRoom/list/$', 'person.views.ClassroonList'),
url(r'^ClassRoom/modify/(\d+)/$', 'person.views.ClassroonModify'),
)

如同加入时候的问题,我们这里面使用的仍然是最原始的sql语句,我们相同能够给他改动成为model的方式:

def ClassroonModify(request,id1):
cursor=connection.cursor()
Classroon=ClassRoom.objects.get(id=id1)
old_name = Classroon.name
old_tutor = Classroon.tutor
cursor.close()
if 'name' in request.GET and request.GET['name'] and 'tutor' in request.GET and request.GET['tutor']:
new_name = request.GET['name']
new_tutor = request.GET['tutor']
Classroon.name=new_name
Classroon.tutor=new_tutor
Classroon.save()
return render_to_response('person/Classroom_Modify_results.html',
{'old_name': old_name,'old_tutor':old_tutor,'new_name':new_name,'new_tutor':new_tutor})
else:
return render_to_response('person/Classroom_Modify.html', {'error': True,'id':id1,'name':old_name,'tutor':old_tutor})

这样看起来是不是简便多了?我们打开 页面看看效果吧 :

接下来我们来做删除的功能,首先改动列表页的模板。增加一列删除button:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>数据库操作简单表的加入</title>
</head>
<body>
<h1>这里是Classroom的管理页面</h1>
<table border="1" cellpadding="10">
<tr>
<td align="center">序号</td>
<td align="center">班级名称</td>
<td align="center">导师姓名</td>
<td align="center">操作</td>
</tr>
{% for myclass in ClassroonList%}
<tr>
<td align="right">{{ myclass.id }}</td>
<td align="right">{{ myclass.name }}</td>
<td align="right">{{ myclass.tutor }}</td>
<td align="right"><input type="button" onClick="Modify({{ myclass.id }})" value="改动">
<input type="button" onClick="Delete({{ myclass.id }})" value="删除">
</td>
</tr>
{% endfor %}
</table>
<script language="javascript">
function Modify(id)
{
location.href='../modify/'+id
} function Delete(id)
{
location.href='../delete/'+id
} </script>
</body>
</html>

Classroom_Delete_results.html:

<html>
<head>
<title>查询用户结果页</title>
</head>
<body>
<table border="1" cellpadding="5"><tr>
<td>班级:{{name}}删除成功 !</td></tr>
<tr>
<td><a href="http://127.0.0.1:8000/ClassRoom/list/">点击返回</a></td>
</tr>
</table>
</body>
</html>

改动视图:

def ClassroonDelete(request,id1):
cursor=connection.cursor()
Classroon=ClassRoom.objects.get(id=id1)
old_name = Classroon.name
Classroon.delete()
ClassroonList=ClassRoom.objects.all()
cursor.close()
  return render_to_response('person/Classroom_Delete_results.html',{'name':old_name})

配置urls.py:

from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover() urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Bidding.views.home', name='home'),
# url(r'^Bidding/', include('Bidding.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^hello/$', 'Bidding.views.hello'),
url(r'^time/$', 'Bidding.views.current_datetime'),
url(r'^time/plus/(\d{1,2})/$', 'Bidding.views.hours_ahead'),
url(r'^hello_base/$', 'Bidding.views.hello_base'),
url(r'^request_test/$', 'Bidding.views.request_test'),
url(r'^UsersSearch/$', 'Bidding.Users.views.search_form'),
url(r'^search/$', 'Bidding.Users.views.search'),
url(r'^ClassRoom/add/$', 'person.views.ClassroonAdd'),
url(r'^ClassRoom/list/$', 'person.views.ClassroonList'),
url(r'^ClassRoom/modify/(\d+)/$', 'person.views.ClassroonModify'),
url(r'^ClassRoom/delete/(\d+)/$', 'person.views.ClassroonDelete'),
)

到此,我们就做好了一个简单的表的加入、删除、改动的操作。

Python+Django+SAE系列教程13-----MySQL记录的添\删\改的更多相关文章

  1. Python+Django+SAE系列教程17-----authauth (认证与授权)系统1

    通过session,我们能够在多次浏览器请求中保持数据,接下来的部分就是用session来处理用户登录了. 当然,不能仅凭用户的一面之词,我们就相信,所以我们须要认证. 当然了,Django 也提供了 ...

  2. Python+Django+SAE系列教程12-----配置MySQL数据库

    由于SAE上支持的是Mysql,首先我们要在本地配置一个Mysql的环境 ,我在网上找到MySQL-python-1.2.4b4.win32-py2.7.exe,并双击 安装 选择典型安装 安装结束后 ...

  3. Python+Django+SAE系列教程15-----输出非HTML内容(图片/PDF)

    一个Django视图函数 必须 接受一个HttpRequest 实例作为它的第一个參数 返回一个HttpResponse 实例 从一个视图返回一个非HTML 内容的关键是在构造一个 HttpRespo ...

  4. Python+Django+SAE系列教程9-----Django的视图和URL

    第三.四.五章介绍的就是Django中MVC的视图.模板.模型了. 首先来看视图(view),在用Django生成的站点目录中,创建一个view.py文件,这个文件開始是空的.然后我们输入下面内容: ...

  5. Python+Django+SAE系列教程11-----request/pose/get/表单

    表单request,post,get 首先我们来看看Request对象,在这个对象中包括了一些实用的信息,学过B/S开发的人来说这并不陌生,我们来看看在Django中是怎样实现的: 属性/方法 说明 ...

  6. Python+Django+SAE系列教程10-----Django模板

    在本章中,我们开始模板,在前面的章节,您可能已经注意到,我们回到文本的方式有点特别的示例视图. 那.HTML直接在硬编码 Python 其中代码. 这的确是一个小BT. def current_dat ...

  7. Python+Django+SAE系列教程6-----本地配置Django

    前五章.我们介绍了Python的语法,本章開始介绍Django. Python的Web框架有非常多,有Django.web2py.tornado.web.py等.我们这里选 则Django.至于这些框 ...

  8. Python+Django+SAE系列教程16-----cookie&amp;session

    本章我们来解说cookie和session ,这两个东西相信大家一定不陌生,概念就不多讲了,我们直接来看其使用方法,首先是cookie,我们在view中加入三个视图,一个是显示cookie的,一个是设 ...

  9. Python+Django+SAE系列教程14-----使表单更安全

    还记得我们上一章提到过的加入页面吗? watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaGVtZW5nMTk4MA==/font/5a6L5L2T/fonts ...

随机推荐

  1. Mybatis 源码分析之一二级缓存

    一级缓存 其实关于 Mybatis 的一级缓存是比较抽象的,并没有什么特别的配置,都是在代码中体现出来的. 当调用 Configuration 的 newExecutor 方法来创建 executor ...

  2. React Native 系列(三)

    前言 本系列是基于React Native版本号0.44.3写的,相信大家看了本系列前面两篇文章之后,对于React Native的代码应该能看懂一点点了吧.本篇文章将带着大家来认识一下React N ...

  3. codevs 1044 拦截导弹 1999年NOIP全国联赛提高组

    1044 拦截导弹 1999年NOIP全国联赛提高组  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 黄金 Gold 题解       题目描述 Description 某国为 ...

  4. Makefile-有三个非常有用的变量。分别是$@,$^,$<代表的意义

    $@ 代表目标文件,$^ 代表所有的依赖文件,$< 代表第一个依赖文件. # 这是简化后的Makefilemain:main.o mytool1.o mytool2.o gcc -o $@ $^ ...

  5. bzoj 1468

    大概思路:树点分治,重心树中每个重心维护一个总的平衡树,树中保存属于该重心的点到该重心的距离,然后对于去掉该重心后形成的子树分别再保存一份. 用这种方式实现的话,还可以支持修改与多次查询,每次操作都是 ...

  6. 内功心法 -- java.util.LinkedList<E> (2)

    写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------下文主要对java.util ...

  7. python开发_zlib_完整版_博主推荐

    ''' python中的zlib模块提供了压缩和解压缩的方法 实现功能: 读取一个文件的内容,然后把该文件的内容以字符串的形式返回 然后对返回回来的字符串进行压缩处理,然后写入到另一个文件中 同时,也 ...

  8. layoutit note

    Head: JavaScript -> Navbar Menu: JavaScript  -> Collapse Compnents -> Panels Compnents -> ...

  9. SqlServer项目经验:介质集有2个介质簇,但只提供了1个。必须提供所有成员

    在对数据库备份与还原的过程中,我遇到一个问题“介质集有2个介质簇,但只提供了1个.必须提供所有成员”,下面详细的介绍一下遇到问题的经过与问题解决的方法! 一.备份与还原遇到的问题描述与解决方法: 前两 ...

  10. HAproxy + keepalived 实现双机热备

    一.HAProxy简介: HAProxy提供高可用性.负载均衡以及基于TCP和HTTP应用的代理,支持虚拟主机,它是免费.快速并且可靠的一种解决方案.HAProxy特别适用于那些负载特大的web站点, ...