1. 程式人生 > >Django_簡單的數據庫交互案例

Django_簡單的數據庫交互案例

length number bject mysql sel 簡單 attribute comm mysqldb

https://www.jianshu.com/p/bd0af02e59ba

一、頁面展示

做一個簡單的數據庫交換的練習案例


技術分享圖片 頁面.png

二、創建mysql 表

(1)創建django
(2)創建app文件python mange.py startapp cmdb
(3)創建數據庫,在project同名的配置的 init.py文件中配置mysql連接

import pymysql
pymysql.install_as_MySQLdb() 

(4)在setting.py 中配置mysql 連接,找到DATABASES

DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.mysql‘,
        ‘NAME‘: ‘testuser‘,
        ‘USER‘:‘root‘,
        ‘PASSWORD‘:‘root‘,
        ‘HOST‘:‘localhost‘,
        ‘PORT‘: ‘3306‘,
    }
}

(5)在setting文件下配置INSTALLED_APPS加入cmdb模塊

INSTALLED_APPS = [
    ‘django.contrib.admin‘,
    ‘django.contrib.auth‘,
    ‘django.contrib.contenttypes‘,
    ‘django.contrib.sessions‘,
    ‘django.contrib.messages‘,
    ‘django.contrib.staticfiles‘,
    ‘cmdb‘,
]

(6)根據CODEFIRST創建表,在app models.py 創建類

from django.db import models

# Create your models here.
class user_info(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=64)

(7)創建新的遷移策略文件python manage.py makemigrations
(8)生成數據庫表python manage.py migrate

三、url 配置

(1)在project 文件的url配置,url分發,分發到指定的app

from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘cmdb/‘, include(‘cmdb.urls‘))
]

(2)在指定的app文件下創建urls.py文件

from django.conf.urls import url,include
from cmdb import views
urlpatterns = [
    #登陸url
    url(r‘login‘, views.login),
    #主界面展示url
    url(r‘index‘, views.index),
    #展示所用戶信息url
    url(r‘user_info‘, views.user_info),
    #展示個人信息的url
    url(r‘user-(?P<nid>\d+)‘,views.user_per),
    #刪除個人信息的url
    url(r‘delete-(?P<nid>\d+)‘,views.user_delete),
]

四、views 層邏輯編寫
(1)登陸主要用到了models.user_info.objects.filter(username=u, password=p).first()

def login(request):
    if request.method == ‘GET‘:
        return render(request,‘login.html‘,{‘msg‘:‘‘})
    elif request.method == ‘POST‘:
        u = request.POST.get(‘user‘,None)
        p = request.POST.get(‘pwd‘,None)
        if u and p :
            #select * from cmdb_user_info where username=u password=p
            obj = models.user_info.objects.filter(username=u, password=p).first()
            if obj:
                #重定向到cmdb/index url 上,url分發到index方法上
                return redirect(‘/cmdb/index‘)
            else:
                msg = ‘用戶名密碼錯誤‘
                return render(request,‘login.html‘,{‘msg‘:msg})
        else:
            return render(request, ‘login.html‘, {‘msg‘: ‘‘})

(2)主頁面展示

def index(request):
    return render(request,‘index_u.html‘)

(3)用戶信息的增加/展示
主要用到了

#select * from cmdb_user_info
obj = models.user_info.objects.all()

#inster into cmdb_user_info(username,password) values(u,p)
models.user_info.objects.create(username=u,password=p)
def user_info(request):
    if request.method == ‘GET‘:
        #select * from cmdb_user_info
        obj = models.user_info.objects.all()
        return render(request,‘index.html‘,{‘user‘:obj})
    elif request.method == ‘POST‘:
        u = request.POST.get(‘user‘)
        p = request.POST.get(‘pwd‘)
        #inster into cmdb_user_info(username,password) values(u,p)
        models.user_info.objects.create(username=u,password=p)
        return redirect(‘/cmdb/user_info‘)

(4)刪除
主要用到

 #刪除 delete from 表 where id=2
 obj = models.user_info.objects.filter(id=nid).delete()
def user_delete(request, nid):
    #刪除 delete from 表 where id=2
    obj = models.user_info.objects.filter(id=nid).delete()
    return redirect(‘/cmdb/user_info‘)

四、templates
(1)login頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="{{ request.path_info }}" method="post">
    <input type="text" name="user">
    <input type="password" name="pwd">
    <span>{{ msg }}</span>
    <input type="submit">
</form>
</body>
</html>

(2)index 頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>

          body{
            margin: 0;
        }
        .header{
            height: 48px;
            background-color: aquamarine;
            color: white;
        }
        .conleft{
            position: absolute;
            top: 48px;
            width: 200px;
            left: 0;
            bottom: 0;
            background-color:chocolate;
        }
        .conright{
            position: absolute;
            left: 200px;
            bottom: 0px;
            right: 0px;
            top: 48px;
            overflow: auto;
            background-color: burlywood;
        }
    </style>
</head>
<body>
<div class="header">歡迎</div>
<div class="con">
    <div class="conleft">
        <a href="/cmdb/user_info">用戶管理</a>
    </div>
    <div class="conright">

    </div>
</div>
<div></div>
</body>
</html>

(3)用戶信息展示頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>

          body{
            margin: 0;
        }
        .header{
            height: 48px;
            background-color: aquamarine;
            color: white;
        }
        .conleft{
            position: absolute;
            top: 48px;
            width: 200px;
            left: 0;
            bottom: 0;
            background-color:chocolate;
        }
        .conright{
            position: absolute;
            left: 200px;
            bottom: 0px;
            right: 0px;
            top: 48px;
            overflow: auto;
            background-color: burlywood;
        }
    </style>
</head>
<body>
<div class="header">歡迎</div>
<div class="con">
    <div class="conleft">
        <a href="/cmdb/user_info">用戶管理</a>
    </div>
    <div class="conright">
        <form action="{{ request.path_info}}" method="post">
            <input type="text" name="user">
            <input type="text" name="pwd">
            <input type="submit" >
        </form>
        {% for i in user %}
            <a href="/cmdb/user-{{ i.id }}">{{ i.username }}
            <a href="/cmdb/delete-{{ i.id }}">刪除</a>

            <br>
        {% endfor %}
    </div>
</div>
<div></div>
</body>
</html>

(4)個人信息更改頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>

          body{
            margin: 0;
        }
        .header{
            height: 48px;
            background-color: aquamarine;
            color: white;
        }
        .conleft{
            position: absolute;
            top: 48px;
            width: 200px;
            left: 0;
            bottom: 0;
            background-color:chocolate;
        }
        .conright{
            position: absolute;
            left: 200px;
            bottom: 0px;
            right: 0px;
            top: 48px;
            overflow: auto;
            background-color: burlywood;
        }
    </style>
</head>
<body>
<div class="header">歡迎</div>
<div class="con">
    <div class="conleft">
        <a href="/cmdb/user_info">用戶管理</a>
    </div>
    <div class="conright">
        <p>用戶信息</p>
        <form action="{{ request.path_info }}" method="post">
        <input type="text" value="{{ i.username }}" name="user">-
        <input type="text" value="{{ i.password }}" name="pwd">
        <input type="submit">編輯</a>
        </form>
    </div>
</div>
<div></div>
</body>
</html>


作者:兩點半的雜貨鋪
鏈接:https://www.jianshu.com/p/bd0af02e59ba
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並註明出處。

Django_簡單的數據庫交互案例