zoukankan      html  css  js  c++  java
  • python-day70--django-Mysql-单表增删改查

    项目名:bookmanage

    app01文件夹 内的 __init__.py

    import pymysql
    
    pymysql.install_as_MySQLdb()
    View Code

    app01文件夹 内的models.py

    from django.db import models
    
    # Create your models here.
    class Info(models.Model):
        id=models.AutoField(primary_key=True)
        name=models.CharField(max_length=32)
        author=models.CharField(max_length=32)
        pubDate=models.DateField()
        price=models.DecimalField(max_digits=5, decimal_places=2)
    View Code

    app01文件夹 内的views.py

    from django.shortcuts import render,redirect
    from app01 import  models
    # Create your views here.
    def chaxun(request):
        userDict=models.Info.objects.all()
        return render(request,'chaxun.html',{'userDict':userDict})
    
    def shanchu(request,idd):
        models.Info.objects.filter(id=idd).delete()
        return redirect('/chaxun/')
    
    def tianjia(request):
        if request.method=='POST':
            name=request.POST.get('name')
            author=request.POST.get('author')
            date=request.POST.get('date')
            price=request.POST.get('price')
    
            models.Info.objects.create(name=name,author=author,pubDate=date,price=price)
            return redirect('/chaxun/')
    
        return render(request,'tianjia.html')
    
    
    def bianji(request):
        if request.method=='POST':
            idi=request.POST.get('id')
            name=request.POST.get('name')
            author=request.POST.get('author')
            date=request.POST.get('date')
            price=request.POST.get('price')
    
            models.Info.objects.filter(id=idi).update(name=name,author=author,pubDate=date,price=price)
            return redirect('/chaxun/')
    
        idi=request.GET.get('id')
        user_info=models.Info.objects.filter(id=idi)[0]
        id=user_info.id
        name=user_info.name
        author=user_info.author
        date=user_info.pubDate
        price=user_info.price
        return render(request,'bianji.html',{'id':id,'name':name,'author':author,'date':date,'price':price})
    View Code

    bookmanage文件夹 内的 settings.py

    """
    Django settings for bookmanage project.
    
    Generated by 'django-admin startproject' using Django 1.11.6.
    
    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 = 'bh#p^+)-^@yc*&v7+_$k2%-#yms-^omlm*ai*cem-ahj!&4o)7'
    
    # 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',
        'app01',
    ]
    
    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 = 'bookmanage.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 = 'bookmanage.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/1.11/ref/settings/#databases
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'bookinfo',  # 你的数据库名称
            'USER': 'root',  #你的数据库用户名
            'PASSWORD': '963.',  #你的数据库密码
            'HOST': '',  #你的数据库主机,留空默认为localhost
            '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/'
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'static'),
    ]
    
    
    TEMPLATE_DIRS = (
        os.path.join(BASE_DIR,  'templates'),
        'app01',
    )
    
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
            },
        },
        'loggers': {
            'django.db.backends': {
                'handlers': ['console'],
                'propagate': True,
                'level': 'DEBUG',
            },
        }
    }
    View Code

    bookmanage文件夹 内的 urls.py

    """biaoge 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 app01 import views
    urlpatterns = [
        url(r'^chaxun/', views.chaxun),
        url(r'^shanchu/(d+)', views.shanchu),
        url(r'^bianji/', views.bianji),
        url(r'^tianjia/', views.tianjia),
    ]
    View Code

    static 文件夹内放 bootstrap及 jQuery 文件

    templates文件夹内的 模板

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title></title>
        <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css"/>
        <script src="/static/jquery-3.2.1.js"></script>
        <script src="/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>
        <style>
            .ccc {
                margin-top: 70px;
            }
    
            .clc {
                height: 30px;
                margin-left: -15px;
                text-align: center;
                line-height: 30px;
                border-radius: 5px;
            }
    
            .menu {
                margin-top: 7px;
    
            }
    
            .panel {
                height: 580px;
            }
    
            .c2 {
                position: fixed;
                left: 1290px;
                top: 580px;
            }
    
            .ccc .row .sidebar {
                padding-top: 20px;
                height: 600px;
                background-color: #f5f5f5;
                margin-top: -20px;
    
            }
        </style>
    </head>
    <body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
                        aria-expanded="false" aria-controls="navbar">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="">图书管理系统</a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="">设置</a></li>
                    <li><a href="">帮助</a></li>
                    <li><a href="">退出</a></li>
                </ul>
                <form class="navbar-form navbar-right">
                    <input type="text" class="form-control" placeholder="搜索...">
                </form>
            </div>
        </div>
    </nav>
    <div class="container-fluid ccc">
        <div class="row">
            <div class="col-sm-3 col-md-2 sidebar">
                <div class="menu">
                    <div class="head bg-primary clc" id="clc1">菜单一</div>
                    <ul class="nav nav-sidebar hide" id="clc4">
                        <li class=""><a href="">Overview <span
                                class="sr-only">(current)</span></a>
                        </li>
                        <li><a href="">Reports</a></li>
                        <li><a href="">Analytics</a></li>
                        <li><a href="">Export</a></li>
                    </ul>
                </div>
                <div class="menu">
                    <div class="head bg-primary clc" id="clc2">菜单二</div>
                    <ul class="nav nav-sidebar hide" id="clc5">
                        <li><a href="">Nav item</a></li>
                        <li><a href="">Nav item again</a></li>
                        <li><a href="">One more nav</a></li>
                        <li><a href="">Another nav item</a></li>
                        <li><a href="">More navigation</a></li>
                    </ul>
                </div>
                <div class="menu">
                    <div class="head bg-primary clc" id="clc3">菜单三</div>
                    <ul class="nav nav-sidebar hide" id="clc6">
                        <li><a href="">Nav item again</a></li>
                        <li><a href="">One more nav</a></li>
                        <li><a href="">Another nav item</a></li>
                    </ul>
                </div>
            </div>
    
    
            <div class="col-sm-9 col-md-10 main">
                <div class="panel panel-primary">
                    <div class="panel-heading">书籍信息</div>
                    <div class="panel-body">
                        <!-- Button trigger modal -->
                        <a href="/tianjia/"><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
                            添加
                        </button></a>
    
                        <table class="table table-hover">
    {#                    <tr>#}
                            <thead>
                            <th>序号</th>
                            <th>书名</th>
                            <th>作者</th>
                            <th>出版日期</th>
                            <th>价钱</th>
                            </thead>
    {#                    </tr>#}
                        {% block tbody %}
    
                        {% endblock tbody %}
                        <div class="row c2">
                            <nav aria-label="Page navigation " class="pull-right c5">
                                <ul class="pagination">
                                    <li>
                                        <a href="#" aria-label="Previous">
                                            <span aria-hidden="true">&laquo;</span>
                                        </a>
                                    </li>
                                    <li><a href="#">1</a></li>
                                    <li><a href="#">2</a></li>
                                    <li><a href="#">3</a></li>
                                    <li><a href="#">4</a></li>
                                    <li><a href="#">5</a></li>
                                    <li>
                                        <a href="#" aria-label="Next">
                                            <span aria-hidden="true">&raquo;</span>
                                        </a>
                                    </li>
                                </ul>
                            </nav>
                        </div>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6 col-md-offset-3" style="margin-top: -40px">
                <hr/>
                <div style="text-align: center">
                    <a href="">关于我们 |</a>
                    <a href="">联系我们 |</a>
                    <a href="">意见与反馈 |</a>
                    <a href="">友情链接 |</a>
                    <a href="">公告</a>
    
                    <div>
                        <div style="font-size: 13px">
                            版权所有:北京Cool科技有限公司
                        </div>
                    </div>
                </div>
    
    
            </div>
        </div>
    </div>
    <script>
    
        $('.clc').on('click', function () {
            $(this).parent().siblings().children('ul').addClass('hide');
            $(this).next().toggleClass('hide');
        })
    
    
    </script>
    </body>
    </html>
    base.html
    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title></title>
            <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css"/>
        <script src="/static/jquery-3.2.1.js"></script>
        <script src="/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
        <div class="row col-md-4 col-md-offset-4" style="margin-top: 100px">
                    {% block form %}
                    {% endblock form %}
        </div>
        </div>
    
    </body>
    </html>
    base2.html
    {% extends 'base2.html' %}
    {% block form %}
        <form action="/bianji/" method="post">
            {% csrf_token %}
            <input type="hidden" name="id" value="{{ id }}"/>
            <div class="form-group">
                <label for="usernaem">书名</label>
                <input type="text" class="form-control item"  id="usernaem" name="name" value="{{ name }}">
            </div>
    
            <div class="form-group">
                <label for="age">作者</label>
                <input type="text" class="form-control item" id="age" name="author" value="{{ author }}">
            </div>
            <div class="form-group">
                <label for="gender">出版时间</label>
                <input type="date" class="form-control item" id="gender" name="date" value="{{ date|date:'Y-m-d' }}">
            </div>
                    <div class="form-group">
                <label for="gender1">价格</label>
                <input type="text" class="form-control item" id="gender1" name="price" value="{{ price }}">
            </div>
            <div class="pull-right"><a href="/chaxun/"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button></a>
            <input type="submit" class="btn btn-primary"/>
    
        </div>
        </form>
    {% endblock form %}
    bianji.html
    {% extends "base.html" %}
    {% block tbody %}
        <tbody>
        {% for user_info in userDict %}
            <tr>
                <td>{{ forloop.counter }}</td>
                <td>{{ user_info.name }}</td>
                <td>{{ user_info.author }}</td>
                <td>{{ user_info.pubDate|date:'Y-m-d' }}</td>
                <td>{{ user_info.price }}</td>
                <td>
                    <div class="pull-left">
                    <a href="/shanchu/{{ user_info.id }}">
                        <button class="btn btn-danger" >删除</button>
                    </a>
                    </div>
                    <a href="/bianji/?id={{ user_info.id }}">
                        <button class="btn btn-success" style="margin-left: 5px">编辑</button>
                    </a>
                </td>
            </tr>
            </tbody>
        {% endfor %}
    {% endblock tbody %}
    chaxun.html
    {% extends 'base2.html' %}
    {% block form %}
        <form action="/tianjia/" method="post">
            {% csrf_token %}
            <div class="form-group">
                <label for="usernaem">书名</label>
                <input type="text" class="form-control item"  id="usernaem" name="name" placeholder="name">
            </div>
    
            <div class="form-group">
                <label for="age">作者</label>
                <input type="text" class="form-control item" id="age" name="author" placeholder="author">
            </div>
            <div class="form-group">
                <label for="gender">出版时间</label>
                <input type="date" class="form-control item" id="gender" name="date">
            </div>
            <div class="form-group">
                <label for="gender1">价格</label>
                <input type="text" class="form-control item" id="gender1" name="price" placeholder="price">
            </div>
            <div class="pull-right"><a href="/chaxun/"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button></a>
            <input type="submit" class="btn btn-primary"/>
            </div>
        </form>
    {% endblock form %}
    tianjia.html

  • 相关阅读:
    GORM模型(Model)创建
    GORM高级查询
    LogAgent
    安装kafka
    go读取日志tailf
    bubble清单
    go操作kafka
    GORM模型删除
    Vue 父子组件间的传值
    列表和表格
  • 原文地址:https://www.cnblogs.com/liuwei0824/p/7743459.html
Copyright © 2011-2022 走看看