Django之单表的增删改查

 

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+%[email protected]_^+^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>

原文地址:https://www.cnblogs.com/zxmbky/p/9682793.html

时间: 2024-10-04 21:37:46

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

3.django模板,单表ORM增删改查

1.Django模板语法 模板语法: 变量: {{}} 1 深度查询 句点符 2 过滤器 {{val|filter_name:参数}} 标签: {% %} 1.1Django模板使用 from django.shortcuts import render import datetime def index(request): now = datetime.datetime.now() return render(request,"index.html",{"current_t

web day19 Service层处理事务(利用ThreadLocal),TxQueryRunner小工具,单表练习(增删改查操作),分页

Service事务 DAO中不是处理事务的地方,因为DAO中的每个方法都是对数据库的一次操作 在Service中不应该出现Connection,它应该只在DAO中出现, 因为它是JDBC的东西,JDBC的东西是用来连接数据库的 修改JdbcUtils 我们把对事务的开启和关闭放到JdbcUtils中,在Service中调用JdbcUtils的方法来完成事务的处理, 但在Service中就不会再出现Connection这一"禁忌"了. 代码 public class JdbcUtils

【框架】[Hibernate]利用Hibernate进行单表的增删改查-Web实例

转载请注明出处:http://blog.csdn.net/qq_26525215 本文源自[大学之旅_谙忆的博客] 前面两篇博客已经将Hibernate的基础知识讲解得差不多了,差不多到写实例的时候了. 本篇只用hibernate进行单表的增删改查. 应用Hibernate,对students表进行增删改查. service层和DAO层,我都是直接写实现类了(因为这里主要是演示一下Hibernate的使用),如果是开发项目,注意一定要写接口! 准备数据库: 首先准备一个students表: cr

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

牛小妹上周末,一直在尝试如何把数据库的数据弄到界面上.毕竟是新手,搞不出来,文档也看不懂.不过没关系,才刚上大学.今晚我们就来解释下,要把数据搞到界面的第一步.先把数据放到库里,然后再把数据从库里拿出来. 以下内容,参考django官方文档 . 1.创建MODEL 这里和官方文档一致.直接拷出来,放到一个叫models的py文件里面.若是你的项目中没有,一定不要觉得无处写代码.你自己建一个即可 同步数据库: 执行以下命令.不懂的可以参考:django连接mysql python manage.p

Mybatis(一)实现单表的增删改查

1.1 什么是Mybatis MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis .iBATIS一词来源于"internet"和"abatis"的组合,是一个基于Java的持久层框架.iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO). MyBatis参考资料官网:https:/

23Spring_JdbcTemplate来实现单表的增删改查

第一步建表: 第二步:编写product表的实体类 public class produce { private int id; private String name; private String price; /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @

MYSQL基础操作之单表的增删改查

一.添加数据. -- 1.创建表,并插入一定的数据. 1 CREATE TABLE STUDENT( 2 ID INT, 3 USERNAME VARCHAR(20), 4 SERVLET INT, 5 JSP INT, 6 ADDRESS VARCHAR(30) 7 ); 8 INSERT INTO STUDENT VALUES (1,'张三',23,84,'京口区'); 9 INSERT INTO STUDENT VALUES (2,'李四',36,74,'润州区'); 10 INSERT

Hibernate和jsp做数据库单表的增删改查

虽然很基础,但是我转牛角尖了~~~~这是几个文件 1.最重要的.Java文件 1 package com.chinasofti.hibb.struts; 2 3 4 import org.hibernate.Session; 5 import org.hibernate.SessionFactory; 6 import org.hibernate.Transaction; 7 import org.hibernate.cfg.Configuration; 8 import com.chinaso

单表的增删改查实例(图书管理 系统)

一 配置sql (1)在项目下的settings里配置数据库(先在mysql里创建好名叫sthw的库) (2)在项目文件下的__init__.py文件中,用mysql替代默认使用的MySQLdb 二 创建表(字段) (1)在应用app01的models.py文件里创建.写类 (2)数据库同步 在终端(项目文件夹下)输入: Python manage.py makemigrations Python manage.py migrate 四 插入记录 通过Python插入记录有三种: 方式一:配置u