zoukankan      html  css  js  c++  java
  • Django重新整理

    1.母版的继承

    #base
    <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> {% block title %} <title>Title</title> {% endblock %} <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <style> *{ margin: 0; padding: 0; } .header{ 100%; height: 50px; background-color: #369; } </style> </head> <body> <div class="header"></div> <div class="container"> <div class="row"> <div class="col-md-3"> {% block menu %} <div class="panel panel-success"> <div class="panel-heading">Panel heading without title</div> <div class="panel-body"> <p><a href="/index/">首页</a></p> <p><a href="/order/">订单</a></p> <p> <a href="/shopping_list/">商品列表</a></p> </div> </div> {% endblock %} </div> <div class="col-md-9">
    #注意 定义一个盒子:关键字:block 必须是这个字!!!后边加自己起的名字
    #{%block content%} {
    % block content %} <h3>welcome!</h3> {% endblock content%} </div> </div> </div> </body> </html>



    #index,html
    #必须是 extends 这个关键字 ,后边跟着继承的哪个页面
    #{%extends "base.html"%}
    {% extends "base.html" %}

    {% block content %}
    {{ block.super }}

    <div class="jumbotron">
    <h1>Hello, world!</h1>
    <p>...</p>
    <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
    </div>
    {% endblock %}


    {% block title %}
    <title>首页</title>
    {% endblock %}


    2.orm小的项目整理

    2.1新建的项目里先生成表

    #models
    
    class Book(models.Model):
        nid=models.AutoField(primary_key=True)
        title=models.CharField(max_length=32)
        price=models.DecimalField(max_digits=8,decimal_places=2) # 999999.99
        pub_date=models.DateTimeField()  # "2012-12-12"
        publish=models.ForeignKey(to="Publish",on_delete=models.CASCADE)  # 级联删除
        authors=models.ManyToManyField(to="Author")
        def __str__(self):
            return self.title
    
    
    class Publish(models.Model):
        nid = models.AutoField(primary_key=True)
        name=models.CharField(max_length=32)
        email=models.CharField(max_length=32)
        def __str__(self):
            return self.name
    
    class Author(models.Model):
        nid = models.AutoField(primary_key=True)
        name=models.CharField(max_length=32)
        age=models.IntegerField()
        email=models.CharField(max_length=32)
        ad=models.OneToOneField(to="AuthorDetail",on_delete=models.CASCADE)
        def __str__(self):
            return self.name
    
    class AuthorDetail(models.Model):
        addr=models.CharField(max_length=32)
        tel=models.IntegerField()
        #author=models.OneToOneField("Author",on_delete=models.CASCADE)
        def __str__(self):
            return self.addr

    2.2进行数据库的迁移

    2.3添加表里的数据,先从从表里添加数据,再从主表里添加数据,或者直接粗暴的在数据库里添加

    2.4分配路由,写视图函数

    #urls
    from django.contrib import admin
    from django.urls import path,re_path
    
    from app01 import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
       path("books/",views.book_view),
        re_path("^$",views.book_view),
        path("books/add/",views.book_add),
        re_path("^books/edit/(?P<edit_book_id>d+)$",views.book_edit),
        re_path("^books/delete/(?P<del_book_id>d+)$",views.book_del),
    ]

    2.5函数

    def book_view(request):
        book_list=Book.objects.all()
        return render(request,"book_view.html",{"book_list":book_list})
    
    def book_add(request):
        if request.method=="GET":
            publish_list=Publish.objects.all()
            author_list=Author.objects.all()
            return render(request,"book_add.html",{"publish_list":publish_list,"author_list":author_list})
        else:
            title=request.POST.get("title")
            price=request.POST.get("price")
            pub_date=request.POST.get("pub_date")
            publish_id=request.POST.get("publish_id")
            authors=request.POST.getlist("authors")
            print(request.POST)
            print(authors)
    
            book=Book.objects.create(title=title,price=price,pub_date=pub_date,publish_id=publish_id)
            book.authors.add(*authors)
            return redirect("/books/")
    
    def book_edit(request,edit_book_id):
        edit_book = Book.objects.filter(pk=edit_book_id).first()
        if request.method=="GET":
            publish_list = Publish.objects.all()
            author_list = Author.objects.all()
            return render(request,"book_edit.html",{"edit_book":edit_book,"publish_list":publish_list,"author_list":author_list})
    
        else:
            title = request.POST.get("title")
            price = request.POST.get("price")
            pub_date = request.POST.get("pub_date")
            publish_id = request.POST.get("publish_id")
            authors = request.POST.getlist("authors")
            print(request.POST)
            print(authors)
            Book.objects.filter(pk=edit_book_id).update(title=title,price=price,pub_date=pub_date,publish_id=publish_id)
            edit_book.authors.set(authors)
    
            return redirect("/books/")
    
    
    
    
    def book_del(request,del_book_id):
        Book.objects.filter(pk=del_book_id).delete()
        return redirect("/books/")

    2.6 tmplates

    #book_add.html
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
         <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
              integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    
    </head>
    <body>
    
    <h3>添加书籍</h3>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="" method="post">
                    {% csrf_token %}
                    <div class="form-group">
                        <label for="title">书籍名称</label>
                        <input class="form-control" type="text" name="title" id="title">
                    </div>
                    <div class="form-group">
                        <label for="price">价格</label>
                        <input class="form-control" type="text" name="price" id="price">
                    </div>
                    <div class="form-group">
                        <label for="pub_date">出版日期</label>
                        <input class="form-control" type="date" name="pub_date" id="pub_date">
                    </div>
                    <div class="form-group">
                        <label for="pub_date">出版社</label>
                        <select name="publish_id" id="" class="form-control">
                            {% for publish in publish_list %}
                                <option value="{{ publish.pk }}">{{ publish.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
    
                    <div class="form-group">
                        <label for="pub_date">作者</label>
                        <select name="authors" id="" class="form-control" multiple>
                            {% for author in author_list %}
                                <option value="{{ author.pk }}">{{ author.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
    
                    <input type="submit" value="提交" class="btn btn-default pull-right">
    
                </form>
    
    
            </div>
        </div>
    </div>
    
    
    
    </body>
    </html>
    
    
    
    
    #book_edit.html
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
         <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
              integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    
    </head>
    <body>
    
    <h3>编辑书籍</h3>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <form action="" method="post">
                    {% csrf_token %}
                    <div class="form-group">
                        <label for="title">书籍名称</label>
                        <input class="form-control" value="{{ edit_book.title }}" type="text" name="title" id="title">
                    </div>
                    <div class="form-group">
                        <label for="price">价格</label>
                        <input class="form-control" value="{{ edit_book.price }}" type="text" name="price" id="price">
                    </div>
                    <div class="form-group">
                        <label for="pub_date">出版日期</label>
                        <input class="form-control" value="{{ edit_book.pub_date|date:'Y-m-d' }}" type="date" name="pub_date" id="pub_date">
                    </div>
                    <div class="form-group">
                        <label for="pub_date">出版社</label>
                        <select name="publish_id" id="" class="form-control">
                            {% for publish in publish_list %}
                                {% if edit_book.publish == publish %}
                                     <option selected  value="{{ publish.pk }}">{{ publish.name }}</option>
                                {% else %}
                                     <option  value="{{ publish.pk }}">{{ publish.name }}</option>
                                {% endif %}
                            {% endfor %}
    
                        </select>
                    </div>
    
                    <div class="form-group">
                        <label for="pub_date">作者</label>
                        <select name="authors" id="" class="form-control" multiple>
                            {% for author in author_list %}
                                {% if author in edit_book.authors.all %}
                                   <option selected value="{{ author.pk }}">{{ author.name }}</option>
                                {% else %}
                                   <option value="{{ author.pk }}">{{ author.name }}</option>
                                {% endif %}
                            {% endfor %}
                        </select>
                    </div>
    
                    <input type="submit" value="提交" class="btn btn-default pull-right">
    
                </form>
    
    
            </div>
        </div>
    </div>
    
    </body>
    </html>
    
    
    #book_view.html
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
         <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
        <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
    </head>
    <body>
    
    <h3>查看书籍</h3>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <a href="/books/add/" class="btn btn-primary">添加书籍</a>
                 <table class="table table-bordered table-hover table-striped">
                      <thead>
                            <tr>
                                 <th>编号</th>
                                 <th>书籍名称</th>
                                 <th>价格</th>
                                 <th>出版日期</th>
                                 <th>出版社</th>
                                 <th>作者</th>
                                 <th>操作</th>
                            </tr>
                      </thead>
                     <tbody>
                           {% for book in book_list %}
                           <tr>
                               <td>{{ forloop.counter }}</td>
                               <td>{{ book.title }}</td>
                               <td>{{ book.price }}</td>
                               <td>{{ book.pub_date|date:"Y-m-d" }}</td>
                               <td>{{ book.publish.name }}</td>
                               <td>
                                   {% for author in book.authors.all %}
                                   <span>{{ author.name }}</span>
                                   {% if not forloop.last %}
                                   ,
                                   {% endif %}
                                   {% endfor %}
    
                               </td>
    
                               <td>
                                   <a href="/books/delete/{{ book.pk }}" class="btn btn-danger btn-sm">删除</a>
                                   <a href="/books/edit/{{ book.pk }}" class="btn btn-warning btn-sm">编辑</a>
                               </td>
                           </tr>
    
                           {% endfor %}
    
                     </tbody>
                 </table>
            </div>
        </div>
    </div>
    <script src="/static/js/jquery.js"></script>
    <script>
        $("h3").click(function () {
            $(this).css("color","green")
        })
    </script>
    </body>
    </html>

     3json模块

    3.1json其实就是一个模块,把字符串类型的转换成我们想要的数据类型

    d = {"name":"alex"}
    print(type(d))
    #<class 'dict'>
    
    s = json.dumps(d)
    print(type(s))
    #<class 'str'>
    
    #注意:json中的dumps是把其他数据类型转换成字符串数据类型
    #注意:json中的loads是把字符串数据类型转换成原有的数据类型

    4.AJAX

    4.1利用Ajax请求进行简单的求和(没有动态传参的Ajax)

    #urls
        path('index/', views.index),
    #views中
    def index(request):
        return render(request,"index.html")
    
    #templayes中
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="/static/js/jquery-3.3.js"></script>
    </head>
    <body>
    
    <h4>INDEX页面</h4>
    <button class="btn">提交Ajax</button>
    <p class="show"></p>
    <hr>
    {% csrf_token %}
    <input type="text" id="num1"> + <input id="num2" type="text"> = <input id="ret" type="text"><button class="cal">计算</button>
    
    <script>
    //  传参Ajax请求

    $(".cal").click(function () {

    var num1=$("#num1").val();
    var num2=$("#num2").val();

    $.ajax({
    #返回的地址
    url:"/cal/",
    type:"post",
    data:{
    num1:num1,
    num2:num2,
    csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val()

    },
    success:function (response) {
    console.log(response);
    $("#ret").val(response)
    }

    })


    })
    </script> </body> </html>


    #urls
    path('cal/', views.cal),

    #views中
    def cal(request):
    num1=request.POST.get("num1")
    num2=request.POST.get("num2")
    ret=int(num1)+int(num2)
    return HttpResponse(str(ret))

    4.2利用Ajax进行登录

    4.2.1分配路由写视图函数

    def login(request):
        if request.method == "POST":
            res={"user":None,"error":""}
            user=request.POST.get("user")
            pwd=request.POST.get("pwd")
    
            user_obj=UserInfo.objects.filter(user=user,pwd=pwd).first()
            if user_obj:
                res["user"]=user
            else:
                res["error"]="用户名或者密码错误!"
            return HttpResponse(json.dumps(res))
    
        else:
            return render(reqeust,"login.html")    


    #templades中
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="/static/js/jquery-3.3.js"></script>

    </head>
    <body>


    <form>
    用户名 <input type="text" id="user">
    密码 <input type="password" id="pwd">
    <input type="button" value="提交" id="login_btn"><span class="error"></span>
    {% csrf_token %}

    </form>


    <script>

    $("#login_btn").click(function () {


    // 发送Ajax请求登录认证

    $.ajax({
    url:"/login/",
    type:"post",
    data:{
    #date是客户端往服务器传过去的数据
    user:$("#user").val(),
    pwd:$("#pwd").val(),
    csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val()
    },
    success:function (response) {
    console.log(response); // json字符串
    var res=JSON.parse(response);
    console.log(res);
    if (res.user){
    // 登陆成功
    location.href="/index/"
    }else{
    // 登录失败
    $(".error").html(res.error).css("color","red");
    setTimeout(function () {
    $(".error").html("")
    },1000)
    }

    }
    })
    })

    </script>
    </body>
    </html>
  • 相关阅读:
    2015.2.27 UltraEdit中显示XML结构
    2015.1.31 DataGridView自动滚动到某行
    2015.1.15 利用函数实现将一行记录拆分成多行记录 (多年想要的效果)
    2015.1.15 利用Oracle函数返回表结果 重大技术进步!
    2015.1.15 利用Oracle函数插入表结构 Bulk collect into 不用循环,简洁高效
    2015.1.8 Left join 左连接
    2015.1.10 解决DataGridView SelectionChanged事件自动触发问题
    delphi 遍历窗口
    delphi 访问 protected 属性 哈哈
    clientdataset 读取excel 如果excel 文件不存在的时候 相应的gird 会不显示数据, 鼠标掠过 gird 格子 才会显示数据。 这是一个bug 哈哈
  • 原文地址:https://www.cnblogs.com/lzqrkn/p/9982325.html
Copyright © 2011-2022 走看看