zoukankan      html  css  js  c++  java
  • 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+%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{
                 150px;
            }
            .form-control{
                 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>
     
  • 相关阅读:
    实战:推断mysql中当前用户的连接数-分组筛选
    Codeforces Round #250 (Div. 2) A
    设计模式(3)-对象创建型模式-Abstract Factory模式
    设计模式
    uva 11825 Hackers&#39; Crackdown (状压dp,子集枚举)
    java中不常见的keyword:strictfp,transient
    C++中数组初始化
    Hadoop 开源调度系统zeus(二)
    Python发一个GET请求
    【代码优化】equals深入理解
  • 原文地址:https://www.cnblogs.com/zxmbky/p/9682793.html
Copyright © 2011-2022 走看看