Table of Contents
这里是Classroom的添加页面
这里是Classroom的管理页面
这里是Classroom--{{name}}的修改页面
Home Database Mysql Tutorial Python+Django+SAE系列课程13-MySQL记录的添删改

Python+Django+SAE系列课程13-MySQL记录的添删改

Jun 07, 2016 pm 04:25 PM
series course

Python+Django+SAE系列教程13-----MySQL记录的添\删\改 建立了数据库后,我们就来做一个简单的表( person_classroom )的添加、删除、修改的操作。 首先我们建立一个添加的页面的模板 Classroom_Add.html(添加的表单) 并把它放在 Bidding\templates\person

Python+Django+SAE系列教程13-----MySQL记录的添\删\改

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

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

Classroom_Add.html



    <title>数据库操作简单表的添加</title>


    <h1 id="这里是Classroom的添加页面">这里是Classroom的添加页面</h1>
    {% if error %}
        <p style="color: red;">请输入班级名称和导师姓名</p>
    {% endif %}
   
Copy after login
项目 内容
班级名称:
导师姓名:

Classroom_Add_results.html


    <title>查询用户结果页</title>


    
Copy after login
Copy after login
Copy after login
班级:{{name}}添加成功 !
点击返回
上面的 这个文件时添加后的结果页。

然后建立对应的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})
Copy after login

在修改一下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'),
)
Copy after login

这时我们的添加就做好了,访问一下classroom/add这个 页面,就可以看到结果了。




不过上面我们所说的办法是执行一个原始的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})
Copy after login

这样的方法即简单,有不用我们很多sql的语法,并且最重要的是如果更换数据库类型(sqlserver->oracle),也不会因为受sql语法不一致的影响。

在接下来,我们来做一个列表页,把数据库中的Classroom表的记录以一个表格的形式显示出来。还是从模板先入手,建立一个Classroom_List.html,放入Bidding\templates\person文件夹下:

Classroom_List.html



    <title>数据库操作简单表的添加</title>


    <h1 id="这里是Classroom的管理页面">这里是Classroom的管理页面</h1>
        
Copy after login
Copy after login
Copy after login
{% for myclass in ClassroonList%} {% endfor %}
序号 班级名称 导师姓名
{{ myclass.id }} {{ myclass.name }} {{ myclass.tutor }}

添加视图:

# -*- 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})
Copy after login

配置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'),
)
Copy after login

如同上述讨论的一样,我们现在的视图执行的是一个原始的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})  
Copy after login

如果需要执行where或者order by等操作可以这样:

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

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

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

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

Classroom_List.html



    <title>数据库操作简单表的添加</title>


    <h1 id="这里是Classroom的管理页面">这里是Classroom的管理页面</h1>
        
Copy after login
Copy after login
Copy after login
{% for myclass in ClassroonList%} {% endfor %}
序号 班级名称 导师姓名 操作
{{ myclass.id }} {{ myclass.name }} {{ myclass.tutor }}

建立一个Classroom_Modify.html模板,把它放在Bidding\templates\person文件夹下

Classroom_Modify.html



    <title>数据库操作简单表的修改</title>


    <h1 id="这里是Classroom-name-的修改页面">这里是Classroom--{{name}}的修改页面</h1>
    {% if error %}
        <p style="color: red;">请输入班级名称和导师姓名</p>
    {% endif %}
   
Copy after login
项目 内容
班级名称:
导师姓名:

Classroom_Modify_results.html


    <title>查询用户结果页</title>


    
Copy after login
Copy after login
Copy after login
  修改前 修改后
班级名称: {{old_name}} {{new_name}}
导师姓名: {{old_tutor}} {{new_tutor}}
修改成功!
点击返回

添加视图:

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})
Copy after login

编辑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'),
)
Copy after login

如同添加时候的问题,我们这里面使用的仍然是最原始的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})
Copy after login

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




接下来我们来做删除的功能,首先修改列表页的模板,加入一列删除按钮:



    <title>数据库操作简单表的添加</title>


    <h1 id="这里是Classroom的管理页面">这里是Classroom的管理页面</h1>
        
Copy after login
Copy after login
Copy after login
{% for myclass in ClassroonList%} {% endfor %}
序号 班级名称 导师姓名 操作
{{ myclass.id }} {{ myclass.name }} {{ myclass.tutor }}

Classroom_Delete_results.html:


    <title>查询用户结果页</title>


    
Copy after login
Copy after login
Copy after login
班级:{{name}}删除成功 !
点击返回

修改视图:

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})
Copy after login

配置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'),
)
Copy after login


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


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Xiaomi 15 series full codenames revealed: Dada, Haotian, Xuanyuan Xiaomi 15 series full codenames revealed: Dada, Haotian, Xuanyuan Aug 22, 2024 pm 06:47 PM

The Xiaomi Mi 15 series is expected to be officially released in October, and its full series codenames have been exposed in the foreign media MiCode code base. Among them, the flagship Xiaomi Mi 15 Ultra is codenamed "Xuanyuan" (meaning "Xuanyuan"). This name comes from the Yellow Emperor in Chinese mythology, which symbolizes nobility. Xiaomi 15 is codenamed "Dada", while Xiaomi 15Pro is named "Haotian" (meaning "Haotian"). The internal code name of Xiaomi Mi 15S Pro is "dijun", which alludes to Emperor Jun, the creator god of "The Classic of Mountains and Seas". Xiaomi 15Ultra series covers

The best time to buy Huawei Mate 60 series, new AI elimination + image upgrade, and enjoy autumn promotions The best time to buy Huawei Mate 60 series, new AI elimination + image upgrade, and enjoy autumn promotions Aug 29, 2024 pm 03:33 PM

Since the Huawei Mate60 series went on sale last year, I personally have been using the Mate60Pro as my main phone. In nearly a year, Huawei Mate60Pro has undergone multiple OTA upgrades, and the overall experience has been significantly improved, giving people a feeling of being constantly new. For example, recently, the Huawei Mate60 series has once again received a major upgrade in imaging capabilities. The first is the new AI elimination function, which can intelligently eliminate passers-by and debris and automatically fill in the blank areas; secondly, the color accuracy and telephoto clarity of the main camera have been significantly upgraded. Considering that it is the back-to-school season, Huawei Mate60 series has also launched an autumn promotion: you can enjoy a discount of up to 800 yuan when purchasing the phone, and the starting price is as low as 4,999 yuan. Commonly used and often new products with great value

How to choose between iPhone 15 and iPhone 15 Pro? Nine major differences at once How to choose between iPhone 15 and iPhone 15 Pro? Nine major differences at once Sep 14, 2023 am 08:01 AM

iPhone15 and iPhone15Pro were officially released today. However, as high-end models, the Pro series not only has a higher price, but also has many exclusive features. Consumers must recognize the differences before buying, so as not to discover some problems after buying iPhone15. The function is only available in the Pro series. Although the monitors are equipped with the same display panel, the ProMotion automatic adaptive update frequency technology and the always-on display function are still exclusive to the Pro series. The rest of the iPhone 15 and iPhone 15 Pro series are the same in terms of resolution, contrast, peak brightness, etc. Action button The action button is currently an exclusive design for the iPhone 15 Pro series, allowing users to personalize it.

The 12 pages of linear algebra notes were on the GitHub hot list, and also received an inscription from the great Gilbert Strang. The 12 pages of linear algebra notes were on the GitHub hot list, and also received an inscription from the great Gilbert Strang. Jul 25, 2023 pm 08:13 PM

The key points of linear algebra have already been drawn by someone. There are only 12 pages in total, and half of them are illustrated, so novices don’t have to worry about not understanding it! Now, this note has received 4k+ stars on GitHub and is also on the hot list. The note in the picture is called "The Art of Linear Algebra" and is based on "Linear Algebra for Everyone" by MIT expert Professor Gilbert Strang. Picture Japanese scholar Kenji Hiranabe condensed this 368-page masterpiece into illustrations, made this set of notes and made it open source for free, and was later translated into Chinese by domestic netizen kfliu. The result not only received a good response on GitHub, but was also recognized by the original author and included in the interest of the original book introduction page.

What series are there in the Hall of Fame? What series are there in the Hall of Fame? Feb 04, 2024 am 09:18 AM

Many users who want to buy memory modules want to know what series of memory modules the GALAX Hall of Fame brand has. In fact, this brand currently has three series, namely HOFEXTREME limited edition, HOFEXTREME, and HOFPRORGB. What are the series of Hall of Fame memory: A: HOFEXTREME limited edition, HOFEXTREME, HOFPRORGB. These three memory modules all have relatively good performance. Among them, the HOFEXTREME limited edition has the best performance. Compared with the previous two models, the HOFPRORGB is slightly weaker but the performance is also very good. Hall of Fame memory expansion introduction: 1. Using Samsung B-die particles, which is the king of memory particles and has a long service life.

iPhone 15 Pro and 15 Pro Max new improvements preview iPhone 15 Pro and 15 Pro Max new improvements preview Sep 12, 2023 pm 10:45 PM

Apple will launch four new iPhone models at 1 a.m. on September 13, namely iPhone 15, 15 Plus, 15 Pro and 15 Pro Max. The high-end iPhone 15 Pro and Pro Max will use a new design, and the side material will be changed from stainless steel to titanium. The colors of the Pro series include gray, black, dark blue, white and other options. The screens of iPhone 15 Pro and Pro Max will be slightly larger this year than last year’s 14 Pro and 14 Pro Max. This change is due to Apple's adoption of a new process technology called LIPO (low injection pressure overmolding), which reduces the thickness of the screen frame by about one-third. High-end models will switch to titanium with a matte texture

How to purchase Chinese public education courses How to purchase Chinese public education courses Mar 13, 2024 pm 12:22 PM

Zhonggong Education is a software that focuses on vocational education knowledge and aims to provide users with comprehensive and rich learning resources. Whether you are about to face a vocational exam or want to improve your vocational skills, China Public Education can meet your needs. Our knowledge content covers various types and stages, and is mainly presented in the form of courses to help users systematically learn and master the required knowledge. So how to purchase the online courses you need in the China Public Education App? For users who don’t know yet, please continue reading below! How to buy online courses from China Public Education? 1. Enter the Chinese Public Education on your mobile phone and enter keywords. 2. Select the online course type. 3. Click Buy Now in the lower right corner. 4. Finally, select the payment method and click to confirm payment.

Recommended learning resources for Java concurrent collections: books, courses, and online tutorials Recommended learning resources for Java concurrent collections: books, courses, and online tutorials Feb 19, 2024 pm 05:00 PM

Java concurrent collections are a collection class library in the Java programming language used to manage concurrent access to shared data. Java concurrent collections provide a variety of data structures, such as queues, stacks, maps, and collections. These data structures are thread-safe and can be used in multi-threaded environments. To learn Java concurrent collections, you can refer to the following books, courses and online tutorials: Book: "Java Concurrent Programming in Practice" This is a classic book in the field of Java concurrent programming, co-authored by Brian Goetz and Tim Peierls. This book introduces in detail the usage methods and techniques of Java concurrent collections, covering thread safety, locks, atomic operations, memory visibility, etc. The book "The Art of Concurrent Programming in Java" is written by Doug Le

See all articles