Django框架+apicloud项目 史上最全讲解之实现插入数据到mysql数据库中

背景

1、前端是apicloud项目,也就是web app项目

2、后端是python的Django框架

3、数据库是Mysql数据库


困难点

1、跨域问题

2、Django框架设置内网ip地址


效果如下

代码如下

首先是前端的代码

注意:1、这里的192.168.1.34是我电脑的地址

2、api.ajax跨域一定不能用localhost与127.0.0.1

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport"
          content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0">
    <title></title>
    <link rel="stylesheet" type="text/css" href="../css/api.css"/>
    <link rel="stylesheet" type="text/css" href="../css/common.css"/>
    <style>
        body {
            display: -webkit-box;
            -webkit-box-orient: vertical;
            background-image: url(../image/bg.jpg);
            background-size: 100%;
        }
        header{
            border: none;
        }
        .header {
            padding: 0 15px;
        }
        .cancel {
            background-image: url("../image/[email protected]");
            background-size: 40px;
            background-repeat: no-repeat no-repeat;
            background-position: center;
        }
        .content {
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-box-flex: 1;
        }

        .title {
            color: #FFFFFF;
            text-align: center;
            line-height: 80px;
            font-size: 25px;
            -webkit-box-flex: 1;
        }

        i {
            display: block;
            width: 30px;
            height: 30px;
            background-size: 30px;
            background-repeat: no-repeat no-repeat;
            background-position: center;
        }

        .user {
            background-image: url("../image/[email protected]");
        }

        .password {
            background-image: url("../image/[email protected]");
        }

        .input-wrap {
            padding: 5px 10px;
            display: -webkit-box;
            background-color: rgba(255, 255, 255, 0.8);
        }

        .input-wrap:first-child {
            border-top-left-radius: 5px;
            border-top-right-radius: 5px;
        }

        .input-wrap:last-child {
            border-bottom-left-radius: 5px;
            border-bottom-right-radius: 5px;
        }

        .form {
            margin: 0 20px;
            line-height: 30px;
        }

        .input-wrap input {
            display: block;
            -webkit-box-flex: 1;
            height: 32px;
        }

        input {
            padding-left: 10px;
        }


        .footer, .form {
            -webkit-box-flex: 1;
        }

        #register {
            display: block;
            color: #ffffff;
            margin: 0 40px;
            text-align: center;
            border-radius: 5px;
            height: 40px;
            line-height: 40px;
            margin-top: 15px;
            background-color: #FF7800;
        }
    </style>
</head>
<body>
<header>
    <div class="header ">
        <div tapmode="" class="cancel btn" οnclick="api.closeWin()"></div>
        <div class="title" id="title">注册</div>
        <div tapmode="" class=" btn" οnclick=""></div>
    </div>
</header>
<div class="content">
    <div class="form">
        <div class="input-wrap" style="border-bottom: 1px solid #d4d4d4;">
            <i class="user"></i>
            <input type="text" placeholder="用户名" class="txt" id="username" />
        </div>
        <div class="input-wrap">
            <i class="password"></i>
            <input type="password" placeholder="密码" class="txt" id="password"/>
        </div>
    </div>
    <footer class="footer">
        <div class=" yellow" id="register" tapmode="yellow-btn-active" οnclick="login()">注册并登录</div>
    </footer>

</div>
<script src="../script/api.js"></script>
<script src="../script/zepto.min.js"></script>
<script>
    apiready = function () {
        $api.fixStatusBar($(".header"));
        api.addEventListener({
            name: 'keyback'
        }, function (ret, err) {
            api.closeWidget();
        });
        $(".content").css("height", $("body").height() - $("footer").height() - $(".header").height());
    };

    function login() {
         var userName = $api.val($api.byId('username'));
         var password = $api.val($api.byId('password'));
          alert(userName)
          alert(password)
        if (userName==''||userName==null) {
            api.toast({
          msg:'请输入账号',
          duration: 1000,
          location:'middle'
                     });
                return;
                                          }
        if (password==''||password==null) {
            api.toast({
          msg:'请输入密码',
          duration: 1000,
          location:'middle'
                      });
      return;
                                 };
        // /*** 加载动画 ***/
        // api.showProgress({
        //     title :'',
        //     text :'玩命加载中...',
        //     modal : true
        // });
    //already
    api.ajax({
      url: 'http://192.168.1.34:8000/regedits/',
      method:'post',
      dataType:'json',
      data:{
      values: {
       username: userName,
       password: password
       },
     }
    }, function(ret, err) {
      //  api.hideProgress();
             alert("hahahha");
//         if(ret.data == false){
//             api.toast({
//               msg:'注册失败',
//               duration: 1000,
//               location:'middle'
//          });
//       }else{
 //
//                 api.toast({
//               msg:'注册成功',
//               duration:'1200',
//               localtion:'middle'
//             });

            //     setTimeout(function() {
            //         api.openWin({
            //         name:'login',
            //         url:'../../login.html',
            //         bounces: false,
            //         animation:{
            //             type: "push",
            //             duration:300
            //         }
            //     });
            //     }, 1000);

        /*** 登录异常 ***/
        if (err) {
            api.toast({
            msg:'网络异常,请稍后重试',
            duration:'1300',
            localtion:'middle'
         });
            return;
        }
  })    //ajax
}//login

</script>
</body>
</html>

python后端的Django框架

首先设置了ip地址,以及跨域设置

 跨域设置

"""
"""
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/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '67u!y3m%iahyyr4ws%axcqhz-*+8-wg$nm62lczo+zl=@5cn8!'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['192.168.1.34']
STATIC_URL = '/static/',
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'login.apps.LoginConfig',

]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',  # 注意顺序
    'django.middleware.common.CommonMiddleware',
    #'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',


]
##跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
      'http://localhost:10915',
      'http://192.168.1.34:10915',
      'http://*.*.*:*'
)
CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)
CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)
# 跨域增加忽略
ROOT_URLCONF = 'djpro.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'login/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 = 'djpro.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
    # 默认的sqlite3数据库  一般不用
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    # }
    # 指定使用Mysql数据库
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # mysql数据库
        'HOST': 'localhost',  # 本地地址
        'PORT': 3306,  # 数据库端口
        'USER': 'root',  # 用户名
        'PASSWORD': '123456',  # 用户密码
        'NAME': 'python',  # 数据库名称
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.2/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/2.2/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/2.2/howto/static-files/

STATIC_URL = '/static/'

然后,根据路径

找到对应的代码位置,执行插入数据库操作

from django.shortcuts import render
from django.shortcuts import HttpResponse
import json
from django.http import HttpResponse
from  login.models import usertjn
# Create your views here.
def helloworld(request):
    return render(request,'a.html')
#删除信息
def deleteinfo(request):
    n=request.GET.items()
    for k,v in n:
        nid=v
    print("我要删除的nid:",v)
    usertjn.objects.get(nid=nid).delete()
    return render(request,'login.html')
#完成修改信息
def reupdate(request):
    username=request.POST.get('username')
    nid = request.POST.get('nid')
    password = request.POST.get('password')
    #修改信息
    user=usertjn.objects.get(nid=nid)
    user.name=username
    user.password=password
    user.save()
    #修改信息
    return render(request,'login.html')

#修改信息
def updateinfo(request):
    itm=request.GET.items()
    for k,v in itm:
        if(k=="name"):
            name=v
        elif(k=="nid"):
            nid=v
        else:
            passed=v
    #把用户名与密码传给下一个
    return render(request,'updates.html',{'name':name,'pass':passed,'nid':nid})
#查询所有的用户信息
def queryinfo(request):
    datas=usertjn.objects.all()
    return render(request,'success.html',{'list':datas})
#验证登录
def relogin(request):
    #获取用户名与密码带入数据库中查询一下
    name=request.POST.get('username');
    password=request.POST.get('password');
    rs=usertjn.objects.filter(name=name,password=password)
    if rs.exists():
        if rs.count()>0:
            info="登录成功"
        else:
            info="登录失败"
    else:
        info = "登录失败"
    print("rs:",rs)
    return render(request,'login.html',{'info':info})
#对数据库的Insert
def reg(request):
    print("注册中....")
    name=request.POST.get('username');
    password=request.POST.get('password');
    usertjn.objects.create(name=name,password=password)
    print('用户名:',name,' 密码:',password)
    ret = {'data': 'success'}
    # return render(request, 'a.html')
    return HttpResponse(json.dumps(ret), content_type='application/json')

 打开数据库瞅瞅


发布了90 篇原创文章 · 获赞 1 · 访问量 2669

猜你喜欢

转载自blog.csdn.net/tian_jiangnan/article/details/105367168
今日推荐