Django--鍗曡〃鎿嶄綔

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django--鍗曡〃鎿嶄綔相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/bootstrap' title='bootstrap'>bootstrap   charm   cli   ati   one   pad   鎻愪氦   django   鑾峰彇   

鐩綍

  • Django--鍗曡〃鎿嶄綔
    • 姝ラ
      • 娣诲姞璺敱
      • 鐧诲綍鍔熻兘
      • 娉ㄥ唽鍔熻兘
      • 鐝骇琛ㄧ殑澧炲垹鏀规煡
      • Django--鍗曡〃鎿嶄綔

        浠婂ぉ灏变互涓€涓鐢熺鐞嗙郴缁熶负渚嬶紝鍏堥€氳繃pymysql杩欎釜妯″潡锛岃繘琛屼竴涓崟琛ㄦ搷浣滐紝鏈変互涓嬩袱绉嶆柟寮?/p>

        1. 鏂皍rl鐨勬柟寮忥細鐩存帴鏂板紑涓€涓〉闈㈣繘琛屾搷浣?/li>
        2. ajax妯℃€佹鐨勬柟寮忥細鍦ㄦ湰椤甸潰閫氳繃妯℃€佹鐨勬柟寮忚繘琛屾搷浣?/li>

        姝ラ

        1. 鍒涘缓涓€涓狣jango椤圭洰

          閫氳繃pycharm鍒涘缓鏂伴」鐩?/p>

        2. 杩涜閰嶇疆

          鍦ㄥ垱寤虹殑椤圭洰鐨剆ettings.py鏂囦欢涓紝杩涜閰嶇疆鏂囦欢鐨勬洿鏀?/p>

        3. 鍦╯tatic鏂囦欢涓紩鍏ootstrap锛宩s

        4. 寮€濮嬪啓鍔熻兘

          1. 娣诲姞璺敱
          2. 璁捐妯℃澘
          3. 鍐欏搴旂殑鎺ュ彛鍑芥暟

        娣诲姞璺敱

        urlpatterns = [
            url(r'^login/', login),   # 鐧诲綍
            url(r'^register/', register),  # 娉ㄥ唽
            
            # 鏂皍rl鏂瑰紡
            url(r'^classes/', classes),  # 鏌ヨ鐝骇淇℃伅
            url(r'^add_class/', add_class), # 娣诲姞鐝骇
            url(r'^del_class/', del_class),  # 鍒犻櫎鐝骇
            url(r'^update_class/', update_class),  # 鏇存柊鐝骇
            
            # ajax妯℃€佹鏂瑰紡 
            url(r'^ajax_add_class/', ajax_add_class),  # 娣诲姞
            url(r'^ajax_update_class/', ajax_update_class), # 鏇存柊
        ]

        鐧诲綍鍔熻兘

        # login.html
        
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>鐧诲綍</title>
            
            <!--寮曞叆bootstarp閲岀殑css鏍峰紡-->
            <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
            <style>
                *, body 
                    margin: 0;
                    padding: 0;
                
        
                .body 
                    position: fixed;
                    top: 0;
                    right: 0;
                    left: 0;
                    bottom: 0;
                    background: url("/static/img/5b73957e18ee0.jpg") no-repeat -20px -100px;
                    background-size: 1300px;
                
        
                .head 
                    margin-top: 20px;
                    margin-left: 20px;
                
        
                .title 
                    color: floralwhite;
                    font-size: 40px;
                    font-family: 'Consolas', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;
                
        
                .main 
                    height: 350px;
                    width: 250px;
                    border: 2px solid rgba(138, 138, 138, 0.73);
                    margin-top: 100px;
                    margin-right: 15%;
                    border-radius: 10px;
                    box-shadow: 0 0 10px 0 darkgrey;
                
        
                .main:hover 
                    box-shadow: 0 10px 20px 0 black;
                
        
                .login 
                    height: 30px;
                    font-size: 16px;
                
            </style>
        </head>
        <body>
        <div class="body">
            <div class="head">
                <h1 class="title">瀛︾敓绠$悊绯荤粺</h1>
            </div>
        
            <div class="main container">
                
                <!--form琛ㄥ崟閾炬帴锛屾彁浜ゆ柟寮?->
                <form action="/login/" method="post" class="form-signin">
                    <h3 class="form-signin-heading" style="color: #8c8c8c; margin-top: 20px;">Please sign in</h3>
                    
                     <!--Useraname杈撳叆妗?->
                    <div style="margin-top: 20px;">
                        <span style="font-size: 14px; color: #8c8c8c;">Username</span>
                        <input type="text" name="username" class="form-control login">
                    </div>
                    <br>
                    
                    <!--Password杈撳叆妗?->
                    <div>
                        <span style="font-size: 14px; color: #8c8c8c;">Password</span>
                        <input type="password" name="pwd" class="form-control login">
                    </div>
                    <div style="margin-top: 10px;">
                        <span style="color: red; font-size: 12px;"> data </span>
                    </div>
                    <br>
                    
                    <!--鎻愪氦妗?->
                    <input class="btn btn-primary btn-block" type="submit" value="Login">
                    
                    <!--杩炴帴鍒版敞鍐岄〉闈?->
                    <button class="btn btn-success btn-block"><a href="/register/" style="color: white;text-decoration: none;">Register</a></button>
                </form>
            </div>
        </div>
        </body>
        </html>
        # urls.py
        
        import json
        import random
        import pymysql
        from django.conf.urls import url
        from django.shortcuts import HttpResponse, render, redirect
        
        # 杩炴帴鏁版嵁搴?def mysql(sql, values=None):
            conn = pymysql.connect(
                host='127.0.0.1',
                port=3306,
                user='root',
                password='123',
                database='day55'
            )
        
            cursor = conn.cursor(pymysql.cursors.DictCursor)
        
            if not values:
                res = cursor.execute(sql)
                data = cursor.fetchall()
        
            else:
                res = cursor.execute(sql, values)
                data = cursor.fetchone()
                conn.commit()
        
            return data, res
        
        # 鐧诲綍鍔熻兘
        def login(request):
            
            # 鍒ゆ柇璇锋眰鏂瑰紡
            if request.method == 'GET':
                
                # 閫氳繃render娓叉煋login.html妯℃澘椤甸潰
                return render(request, "login.html")
            else:
                username = request.POST.get('username')
                pwd = request.POST.get('pwd')
        
                # 鍒ゆ柇鐢ㄦ埛杈撳叆瀵嗙爜鏄惁涓虹┖
                if not (username and pwd):
                    data = '鐢ㄦ埛鍚嶅瘑鐮佷笉鑳戒负绌?#39;
                    return render(request, 'login.html', 'data': data)
        
                # 鍒ゆ柇鐢ㄦ埛鏄惁瀛樺湪
                sql = 'select * from user where name=%s'
                res = mysql(sql, (username,))[1]
                if not res:
                    data = '鐢ㄦ埛鍚嶄笉瀛樺湪,璇峰厛娉ㄥ唽'
                    return render(request, 'login.html', 'data': data)
        
                # 楠岃瘉鐢ㄦ埛瀵嗙爜鏄惁姝g‘
                sql = "select pwd from user where name = %s and pwd = %s"
                res = mysql(sql, (username, pwd))[1]
        
                if res:
                    obj = redirect('/classes/')
                    
                    # 浜х敓涓€涓殢鏈虹殑cookie
                    lis = [chr(num) for num in range(48, 123) if
                           num not in [58, 59, 60, 61, 62, 63, 64, 91, 92, 93, 94, 95, 96]]
        
                    val = ''
                    salt = ''
                    for i in range(20):
                        val += random.choice(lis)
                        salt += random.choice(lis)
        
                    # 缁戝畾鍔犲瘑cookie
                    obj.set_signed_cookie('LOGIN', val, salt=salt, max_age=180)
                    return obj
        
                else:
                    data = '鐢ㄦ埛鍚嶅瘑鐮侀敊璇紝鐧诲綍澶辫触'
                    return render(request, 'login.html', 'data': data)
        
                
        # 鐧诲綍瑁呴グ鍣?       
        def deco(func):
            def wrapper(request):
                val = request.COOKIES.get("LOGIN")
        
                if not val:
                    return redirect('/login/')
        
                res = func(request)
                return res
        
            return wrapper

        娉ㄥ唽鍔熻兘

        # redister.html
        
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>娉ㄥ唽</title>
            <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
            <style>
                *, body 
                    margin: 0;
                    padding: 0;
                
        
                .body 
                    position: fixed;
                    top: 0;
                    right: 0;
                    left: 0;
                    bottom: 0;
                    background: url("/static/img/5b73957e18ee0.jpg") no-repeat -20px -100px;
                    background-size: 1300px;
                
        
                .head 
                    margin-top: 20px;
                    margin-left: 20px;
                
        
                .title 
                    color: floralwhite;
                    font-size: 40px;
                    font-family: 'Consolas', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;
                
        
                .main 
                    height: 350px;
                    width: 250px;
                #background-color: black;##opacity: 0.4;# border: 2px solid rgba(138, 138, 138, 0.73);
                    margin-top: 80px;
                    margin-right: 15%;
                    border-radius: 10px;
                    box-shadow: 0 0 10px 0 darkgrey;
                
        
                .main:hover 
                    box-shadow: 0 10px 20px 0 black;
                
        
                .login 
                    height: 30px;
                    font-size: 16px;
                
            </style>
        </head>
        <body>
        <div class="body">
            <div class="head">
                <h1 class="title">瀛︾敓绠$悊绯荤粺</h1>
            </div>
        
            <div class="main container">
                <form action="/register/" method="post" class="form-signin">
                    <h3 class="form-signin-heading" style="color: #8c8c8c; margin-top: 20px;">Please sign in</h3>
                    <div style="margin-top: 20px;">
                        <span style="font-size: 14px; color: #8c8c8c;">Username</span>
                        <input type="text" name="username" class="form-control login">
                    </div>
                    <div>
                        <span style="font-size: 14px; color: #8c8c8c;">Password</span>
                        <input type="password" name="pwd" class="form-control login">
                    </div>
                    <div>
                        <span style="font-size: 14px; color: #8c8c8c;">Age</span>
                        <input type="password" name="age" class="form-control login">
                    </div>
                    <div style="margin-top: 10px;">
                        <span style="color: red; font-size: 12px;"> data </span>
                    </div>
                    <br>
                    <input class="btn btn-primary btn-block" type="submit" value="Register">
                </form>
            </div>
        </div>
        </body>
        </html>
        # urls.py
        
        def register(request):
            
            # 鍒ゆ柇璇锋眰鏂瑰紡
            if request.method == 'GET':
                return render(request, "register.html")
            else:
                # 鑾峰彇淇℃伅post璇锋眰鎼哄甫鐨勪俊鎭?        username = request.POST.get('username')
                pwd = request.POST.get('pwd')
                age = request.POST.get('age')
        
                # 鍒ゆ柇鐢ㄦ埛杈撳叆鐨勬槸鍚︿负绌?        if not (username and pwd and age):
                    data = '鐢ㄦ埛鍚嶃€佸瘑鐮併€佸勾榫勪笉鑳戒负绌?#39;
                    return render(request, 'register.html', 'data': data)
        
                # 鍒ゆ柇鐢ㄦ埛鏄惁瀛樺湪
                sql = 'select * from user where name=%s'
                res = mysql(sql, (username,))[1]
                if res:
                    data = '鐢ㄦ埛鍚嶅凡瀛樺湪,璇烽噸鏂版敞鍐?#39;
                    return render(request, 'register.html', 'data': data)
                
                # 鎶婄敤鎴峰瓨鍏ユ暟鎹簱锛屾敞鍐屾垚鍔熶箣鍚庤烦杞埌鐧诲綍椤甸潰
                sql = "insert into user(name,pwd,age) values(%s,%s,%s)"
                mysql(sql, (username, pwd, age))
                return redirect('/login/')

        鐝骇琛ㄧ殑澧炲垹鏀规煡

        # classes.html
        
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>鐝骇琛?lt;/title>
            <style>
                a 
                    color: black;
                    text-decoration: none;
                
        
                .shadow 
                    position: fixed;
                    left: 0;
                    right: 0;
                    top: 0;
                    bottom: 0;
                    background-color: black;
                    opacity: 0.4;
                    display: none;
                
        
                .add_model, .update_model 
                    position: fixed;
                    height: 300px;
                    width: 500px;
                    left: 500px;
                    top: 100px;
                    background-color: white;
                    display: none;
                
        
                .model 
                    margin-top: 20px;
                    margin-left: 40px;
                
        
            </style>
        </head>
        <body>
        <h2>鐝骇琛?lt;/h2>
        <!--閫氳繃table鏍囩鏄剧ず鐝骇淇℃伅-->
        <table border="1" cellspacing="0">
            <tbody>
            <tr>
                <th>ID</th>
                <th>鐝骇鍚嶇О</th>
                <th>鏇存柊</th>
                <th>鍒犻櫎</th>
            </tr>
                
            <!-- 寰幆鍙栧嚭涓€涓釜鍏冪礌杩涜灞曠ず -->
            % for item in classes %
                <tr>
                    <td> item.id </td>
                    <td> item.cname </td>
                    <td>
                        <button><a href="/update_class/?id= item.id ">鏇存柊</a></button>
                        <button class="ajax_update">ajax鏇存柊</button>
        
                    </td>
                    <td>
                        <button><a href="/del_class/?id= item.id " class="delete">鍒犻櫎</a></button>
        #                <button class="ajax_delete">ajax鍒犻櫎</button>#
                    </td>
                </tr>
            % endfor %
        
            </tbody>
        </table>
        <br><br>
        <button><a href="/add_class/" target="_blank">娣诲姞鐝骇</a></button>
        <button id="ajax_add">ajax娣诲姞鐝骇</button>
        </div>
        </body>
        </html>
        # add_class.html
        
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>澧炲姞鐝骇</title>
            <style>
                a 
                    color: black;
                    text-decoration: none;
                
            </style>
        </head>
        <body>
        <h2>澧炲姞鐝骇</h2>
        <form action="/add_class/" method="post">
            鐝骇鍚嶇О锛?lt;input type="text" name="classname">
            <input type="submit" value="鎻愪氦">
            <button><a href="/classes/">鍙栨秷</a></button>
            <br><span style="color:red; font-size: 12px;"> data </span>
        </form>
        </body>
        </html>
        # update_class.html
        
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>鐝骇鏇存柊</title>
            <style>
                a 
                    color: black;
                    text-decoration: none;
                
            </style>
        </head>
        <body>
        <h2>鏇存柊鐝骇鍚嶅瓧</h2>
        <form action="/update_class/" method="post">
            <input type="hidden" name="id" value=" id ">
            鐝骇鍚嶇О锛?lt;input type="text" name="classname" value=" cname ">
            <input type="submit" value="鏇存柊">
            <button><a href="/classes/">鍙栨秷</a></button>
            <br><span style="color: red; font-size: 12px"> data </span>
        </form>
        </body>
        </html>
        # urls.py
        
        # 鑾峰彇鐝骇淇℃伅
        @deco
        def classes(request):
            sql = 'select * from classes order by id'
            classes = mysql(sql)[0]
            return render(request, 'classes.html', 'classes': classes)
        
        # 娣诲姞鐝骇
        @deco
        def add_class(request):
            if request.method == 'GET':
                return render(request, 'add_class.html')
            else:
                classname = request.POST.get('classname')
        
                if not classname:
                    data = '鐝骇鍚嶇О涓嶈兘涓虹┖'
                    return render(request, 'add_class.html', 'data': data)
        
                sql = "select * from classes where cname=%s"
                res = mysql(sql, (classname,))[0]
                if res:
                    data = '鐝骇鍚嶇О宸插瓨鍦?#39;
                    return render(request, 'add_class.html', 'data': data)
        
                sql = 'insert into classes(cname) values(%s)'
                res = mysql(sql, (classname,))[1]
                # print(res)
        
                if res:
                    return redirect('/classes/')
                else:
                    return render(request, 'add_class.html')
        
        # 鍒犻櫎鐝骇
        @deco
        def del_class(request):
            id = request.GET.get('id')
        
            sql = 'delete from students where cid=%s'
            res = mysql(sql, (id,))
        
            sql = 'delete from classes where id = %s'
            res = mysql(sql, (id,))
        
            return redirect('/classes/')
            # return HttpResponse('ok')
        
        # 鏇存柊鐝骇
        @deco
        def update_class(request):
            if request.method == "GET":
                id = request.GET.get('id')
                # print(id)
                sql = "select * from classes where id = %s"
                classinfo = mysql(sql, (id,))[0]
                # print(classname)
                return render(request, 'update_class.html', classinfo)
                # return render(request,'update_class.html','classinfo': classinfo)
            else:
                id = request.POST.get('id')
                classname = request.POST.get('classname')
        
                # print(id, classname, 2222)
        
                if classname:
        
                    sql = 'select * from classes where cname=%s'
                    res = mysql(sql,(classname,))[0]
        
                    if res:
                        data = '鐝骇鍚嶇О宸插瓨鍦?#39;
                        return render(request, 'update_class.html', 'data': data)
        
                    sql = "update classes set cname=%s where id=%s"
                    res = mysql(sql, (classname, id))[1]
        
                    return redirect('/classes/')
                else:
                    data = '鐝骇鍚嶇О涓嶈兘涓虹┖'
                    return render(request, 'update_class.html', 'data': data)

        # classes.html <!--鐩存帴鍔犲湪classes.html椤甸潰閲岄潰--> # 閬僵灞?# <div class="shadow"></div> # 寮瑰嚭妗嗗眰 # <div class="add_model"> # <input type="hidden" name="class_id"># <div class="model"> 鐝骇鍚嶇О锛?lt;input type="text" name="classname" id="add_class"> <button id="add">鎻愪氦</button> <button class="add_cancel">鍙栨秷</button> <br><span id="error" style="color:red; font-size: 12px;"></span> </div> </div> <div class="update_model"> <div class="model"> <input type="hidden" name="id" id="up_id"> 鏂扮殑鐝骇鍚嶇О锛?lt;input type="text" name="classname" id="up_name"> <button id="update">鎻愪氦</button> <button class="up_cancel">鍙栨秷</button> <br><span id="up_error" style="color:red; font-size: 12px;"></span> </div> # 瀵煎叆jQuery # <script src="/static/js/jquery-1.12.4.min.js"></script> # 鍒犻櫎 # <script> $('.delete').click(function () res = window.confirm('鏄惁鍒犻櫎鐝骇'); return res; ); </script> #澧炲姞# <script> $('#ajax_add').click(function () $('.shadow, .add_model').css('display', 'block'); ); $('.add_cancel').click(function () $('.shadow, .add_model').hide(); window.location.href = '/classes/'; ); $('#add').click(function () var classname = $('#add_class').val(); $.ajax( type: 'POST', url: '/ajax_add_class/', data: 'classname': classname, success: function (data) var res = JSON.parse(data); if (res['code'] == 10000) alert(res['msg']); window.location.href = '/classes/'; else $('#error').text(res['msg']); ) ); </script> #鏇存柊# <script> $('.ajax_update').click(function () $('.shadow, .update_model').show(); var info = $(this).parent().prevAll(); var classname = info[0].innerText; var id = info[1].innerText; $('#up_name').val(classname); $('#up_id').val(id) ); $('.up_cancel').click(function () $('.shadow, .update_model').hide(); window.location.href = '/classes/'; ); $('#update').click(function () var classname = $('#up_name').val(); var id = $('#up_id').val(); console.log(classname,id); $.ajax( type: 'POST', url: '/ajax_update_class/', data: 'classname': classname, 'id': id, success: function (data) var res = JSON.parse(data); if (res['code'] == 10000) alert(res['msg']); window.location.href = '/classes/'; else $('#up_error').text(res['msg']); ) ); </script>
        # urls.py
        
        # ajax娣诲姞
        @deco
        def ajax_add_class(request):
            classname = request.POST.get('classname')
        
            # 浠son鏍煎紡杩涜鏂囦欢浼犺緭
            res = 'code': None, 'msg': None
            if not classname:
                res['code'] = 10001
                res['msg'] = '鐝骇鍚嶅瓧涓嶈兘涓虹┖'
                return HttpResponse(json.dumps(res))
        
            sql = 'select * from classes where cname=%s'
            resp = mysql(sql, (classname,))[0]
        
            if resp:
                res['code'] = 10001
                res['msg'] = f'鐝骇--classname--宸插瓨鍦?#39;
                return HttpResponse(json.dumps(res))
        
            sql = "insert into classes(cname) values(%s)"
            resp = mysql(sql, (classname,))[1]
            res['code'] = 10000
            res['msg'] = f'鐝骇--classname--娣诲姞鎴愬姛'
            return HttpResponse(json.dumps(res))
        
        # ajax鏇存柊
        @deco
        def ajax_update_class(request):
            classname = request.POST.get('classname')
            id = request.POST.get('id')
        
            res = 'code': None, 'msg': None
            if not classname:
                res['code'] = 10001
                res['msg'] = '鐝骇鍚嶅瓧涓嶈兘涓虹┖'
                return HttpResponse(json.dumps(res))
        
            sql = 'select * from classes where cname=%s'
            resp = mysql(sql, (classname,))[0]
        
            if resp:
                res['code'] = 10001
                res['msg'] = f'鐝骇--classname--宸插瓨鍦?#39;
                return HttpResponse(json.dumps(res))
        
            print(res)
            sql = "update classes set cname=%s where id=%s"
            resp = mysql(sql, (classname, id))[1]
            res['code'] = 10000
            res['msg'] = f'鐝骇--classname--鏇存柊鎴愬姛'
            print(res)
            return HttpResponse(json.dumps(res))

        以上是关于Django--鍗曡〃鎿嶄綔的主要内容,如果未能解决你的问题,请参考以下文章

        Django涔婳RM鎿嶄綔

        Java鎿嶄綔JSON鏁版嵁--Gson鎿嶄綔JSON鏁版嵁

        鎿嶄綔绯荤粺-鎿嶄綔绯荤粺-鍐呮牳涓殑灞忓箷鎵撳嵃(涓?

        鏁版嵁搴撶瑪璁?馃搾 MySQL鍩虹鎿嶄綔鍛戒护 鍒嗙被娓呮櫚

        鑺傜偣鎿嶄綔

        pandas 鎿嶄綔-2