books/urls.py

 
"""books URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from book_obj import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^books/', views.book),
url(r'^add_books/', views.add_book),
url(r'^del_books/', views.del_book),
url(r'^edit_books/', views.edit_book),
]
 

books/settings.py

 
"""
Django settings for books project. Generated by 'django-admin startproject' using Django 1.11.15. For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
""" import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '@9_h!7w793k^6uw95^ooybm1+xx4&)u35n%cnfl+%sz@7_^+^8' # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'book_obj.apps.BookObjConfig',
] MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
] ROOT_URLCONF = 'books.urls' TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
] WSGI_APPLICATION = 'books.wsgi.application' # Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "book_db",
"HOST" : "127.0.0.1",
"USER" : "root",
"PASSWORD" : "333",
"PORT" : 3306,
}
} # Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
] # Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/'
STATIC_DIRS = [
os.path.join(BASE_DIR,"static")
]
 

book_obj/__init__.py

import pymysql
pymysql.install_as_MySQLdb()

book_obj/models.py

 
from django.db import models

# Create your models here.
class Pbook (models.Model):
name = models.CharField(max_length=32,unique=True) def __str__(self):
return self.name
 

book_obj/views.py

 
from django.shortcuts import render,HttpResponse,redirect
from book_obj import models # Create your views here.
def book(request):
all = models.Pbook.objects.all().order_by("id")
return render(request,"book.html",{"bookconcerns": all}) #增加出版社
def add_book(request):
add_name,err_msg = "",""
if request.method =="POST":
add_name = request.POST.get("new_name")
pub_list = models.Pbook.objects.filter(name=add_name)
if add_name and not pub_list:
models.Pbook.objects.create(name=add_name)
print("1")
return redirect("/books/")
if not add_name:
err_msg = "输入内容不能为空"
if pub_list:
err_msg = "出版社已存在"
return render(request,"add_book.html",{"err_name" : add_name,"err_msg" : err_msg}) #删除出版社
def del_book(request):
del_id = request.GET.get("id")
del_list = models.Pbook.objects.filter(id=del_id)
if del_list:
del_list.delete()
return redirect("/books/")
else:
return HttpResponse("删除失败") #编辑出版社
def edit_book(request):
edit_id = request.GET.get("id")
edit_list = models.Pbook.objects.filter(id=edit_id)
err_msg = ""
if request.method == "POST":
edit_name = request.POST.get("new_name")
check_list = models.Pbook.objects.filter(name=edit_name)
if edit_name and edit_list and not check_list:
edit_obj = edit_list[0]
edit_obj.name = edit_name #更改name值
edit_obj.save() #更改后保存在数据库中
return redirect("/books/")
if check_list:
err_msg = "出版社已存在"
if not edit_name:
err_msg = "出版社不能为空"
if edit_list:
edit_obj = edit_list[0]
return render(request,"edit_book.html",{"old_obj" : edit_obj,"err_msg" : err_msg})
else:
return HttpResponse("数据不存在哦")
 

templates/book.html

 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>出版社</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style>
.cc{
margin-left: 90%;
}
</style>
</head>
<body>
<table class="table table-bordered">
<thead>
<tr>
<th>序号</th>
<th>ID</th>
<th>出版社</th>
<th>基操</th>
<th>勿6</th>
</tr>
</thead>
<tbody>
{% for bookconcern in bookconcerns %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ bookconcern.id }}</td>
<td>{{ bookconcern.name }}</td>
<td>
<a href="/del_books/?id={{ bookconcern.id }}">
<button type="button" class="btn btn-danger">删除</button>
</a>
</td>
<td>
<a href="/edit_books/?id={{ bookconcern.id }}">
<button type="button" class="btn btn-warning">编辑</button>
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<a href="/add_books/" class="cc"><button type="button" class="btn btn-primary">增加出版社</button></a>
</body>
</html>
 

templates/add_book.html

 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>增加出版社</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style>
.input-group-addon{
width: 150px;
}
.form-control{
width: 300px;
}
#vv{
position: relative;
left: 500px;
}
</style>
</head>
<body>
<form action="" method="post">
<span>
<span class="input-group-addon">出版社名称:</span>
<input type="text" name="new_name" value="{{ err_name }}" class="form-control" aria-label="Amount (to the nearest dollar)">
<button class="btn btn-primary" id="vv">提交</button>
</span>
<span>{{ err_msg }}</span> </form>
</body>
</html>
 

templates/edit_book.html

 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>编辑页面</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h3>编辑出版社</h3>
<form action="" method="post">
<p>出版社名称:<input type="text" name="new_name" value="{{ old_obj.name }}"></p><span>{{ err_msg }}</span>
<button class="btn btn-warning">提交</button>
</form>
</body>
</html>
 

Django之单表的增删改查的更多相关文章

  1. Django学习笔记(10)——Book单表的增删改查页面

    一,项目题目:Book单表的增删改查页面 该项目主要练习使用Django开发一个Book单表的增删改查页面,通过这个项目巩固自己这段时间学习Django知识. 二,项目需求: 开发一个简单的Book增 ...

  2. python全栈开发day61-django简单的出版社网站展示,添加,删除,编辑(单表的增删改查)

    day61 django内容回顾: 1. 下载: pip install django==1.11.14 pip install -i 源 django==1.11.14 pycharm 2. 创建项 ...

  3. hibernate对单表的增删改查

    ORM: 对象关系映射(英语:Object Relational Mapping,简称ORM,或O/RM,或O/R mapping) 实现对单表的增删改查 向区域表中增加数据: 第一步: 新建一个Da ...

  4. django模型层 关于单表的增删改查

    关于ORM MTV或者MVC框架中包括一个重要的部分,就是ORM,它实现了数据模型与数据库的解耦,即数据模型的设计不需要依赖于特定的数据库, 通过简单的配置就可以轻松更换数据库,这极大的减轻了开发人员 ...

  5. Django学习笔记--数据库中的单表操作----增删改查

    1.Django数据库中的增删改查 1.添加表和字段 # 创建的表的名字为app的名称拼接类名 class User(models.Model): # id字段 自增 是主键 id = models. ...

  6. django 利用ORM对单表进行增删改查

    牛小妹上周末,一直在尝试如何把数据库的数据弄到界面上.毕竟是新手,搞不出来,文档也看不懂.不过没关系,才刚上大学.今晚我们就来解释下,要把数据搞到界面的第一步.先把数据放到库里,然后再把数据从库里拿出 ...

  7. Django中对单表的增删改查

    之前的简单预习,重点在后面 方式一: # create方法的返回值book_obj就是插入book表中的python葵花宝典这本书籍纪录对象   book_obj=Book.objects.creat ...

  8. Django中多表的增删改查操作及聚合查询、F、Q查询

    一.创建表 创建四个表:书籍,出版社,作者,作者详细信息 四个表之间关系:书籍和作者多对多,作者和作者详细信息一对一,出版社和书籍一对多 创建一对一的关系:OneToOne("要绑定关系的表 ...

  9. Django 文件配置、pycharm及django连接数据库、表的增删改查 总结

    静态文件配置 1.你在浏览器中输入网址能够有响应的资源返回给你 是因为后端已经提前给你开设该资源的接口,也就意味着你所能 访问到的资源 都是人家事先定义好的 2.django如何给用户开设资源接口呢? ...

随机推荐

  1. 535 Encode and Decode TinyURL 编码和解码精简URL地址

    详见:https://leetcode.com/problems/encode-and-decode-tinyurl/description/ C++: class Solution { public ...

  2. 083 Remove Duplicates from Sorted List 有序链表中删除重复的结点

    给定一个排序链表,删除所有重复的元素使得每个元素只留下一个.案例:给定 1->1->2,返回 1->2给定 1->1->2->3->3,返回 1->2- ...

  3. html文本框和按钮这些点击时不显示边框的光晕

    直接在样式加:focus{outline:0;}这样子就可以了

  4. Spring AOP初步总结(二)

    该篇为Spring AOP的一个应用案例:系统日志 需求:将任何删除,更改或新增数据库的操作汇总到数据库中 步骤1:编写切面 @Aspect @Component public class SysLo ...

  5. window.close() 关闭当前浏览器页

    function eseFun() { var browserName = navigator.appName; //获取浏览器名称 if(browserName == "Netscape& ...

  6. Java MVC 增删改查 实例

    需求:实现增加新部门的功能,对应数据库表示Oracle的dept表 一.Java MVC 增 实现: 1.视图层(V):注册部门 deptAdd.jsp 在注册新部门页面只需输入“部门名称”和“城市” ...

  7. selenium-Python之鼠标事件

    通过click()来模拟鼠标的单击操作,鼠标还具有鼠标右击,双击,悬停甚至鼠标拖动等功能.在webdriver中,将这些鼠标操作方法封装在ActionChains类提供. ActionChains类提 ...

  8. (二)maven之项目结构

    我们可以看一下Maven项目的大致结构:      项目结构: src/main/java:java源代码文件目录. src/main/resources:资源库,会自动赋值到classes目录里,像 ...

  9. spring框架的总结

    http://www.cnblogs.com/wangzn/p/6138062.html 大家好,相信Java高级工程师对spring框架都很了解吧!那么我以个人的观点总结一下spring,希望大家有 ...

  10. App Store中的开源游戏汇总

    这是国外达人收集的曾经在app store上出现过,或者还在app store上卖的iOS开源游戏的列表,其中代码大部分人你托管在google code或者github上,其中有很多使用Cocos2D ...