Django学习第五天

启动项目命令

python 复制代码
python manage.py runserver

图像验证码生成随机字母或者数字

python 复制代码
import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter


def check_code(width=120, height=40, char_length=5, font_file='ZixunHappyBold.ttf', font_size=28):
    code = []
    img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
    draw = ImageDraw.Draw(img, mode='RGB')

    def rndChar():
        """
        生成随机字母
        :return:
        """
        return chr(random.randint(65, 90))
        # 生成随机数字
        # return str(random.randint(0, 9))

    def rndColor():
        """
        生成随机颜色
        :return:
        """
        return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))

    # 写文字
    font = ImageFont.truetype(font_file, font_size)
    for i in range(char_length):
        char = rndChar()
        code.append(char)
        h = random.randint(0, 4)
        draw.text([i * width / char_length, h], char, font=font, fill=rndColor())

    # 写干扰点
    for i in range(40):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())

    # 写干扰圆圈
    for i in range(40):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())

    # 画干扰线
    for i in range(5):
        x1 = random.randint(0, width)
        y1 = random.randint(0, height)
        x2 = random.randint(0, width)
        y2 = random.randint(0, height)

        draw.line((x1, y1, x2, y2), fill=rndColor())

    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    return img, ''.join(code)


if __name__ == '__main__':
    # 1. 直接打开
    # img,code = check_code()
    # img.show()

    # 2. 写入文件
    # img,code = check_code()
    # with open('code.png','wb') as f:
    #     img.save(f,format='png')

    # 3. 写入内存(Python3)
    # from io import BytesIO
    # stream = BytesIO()
    # img.save(stream, 'png')
    # stream.getvalue()

    # 4. 写入内存(Python2)
    # import StringIO
    # stream = StringIO.StringIO()
    # img.save(stream, 'png')
    # stream.getvalue()

    pass

Ajax请求

Ajax发送get请求

task_list.html

html 复制代码
{% extends 'layout.html' %}

{% block content %}
    <div class="container">
        <h1>任务管理</h1>

        <h3>示例1</h3>
        <input type="button" class="btn btn-primary" value="点击" onclick="clickMe()"/>
    </div>
{% endblock %}

{% block js %}
    <script type="text/javascript">
        function clickMe() {
            $.ajax({
                url: '/task/ajax/',
                type: "get",
                data: {
                    n1: 123,
                    n2: 456
                },
                success: function (res) {
                    console.log(res);
                }
            })
        }
    </script>
{% endblock %}

免除csrf_token认证

Ajax发送post请求

task_list.html

html 复制代码
{% extends 'layout.html' %}

{% block content %}
    <div class="container">
        <h1>任务管理</h1>

        <h3>示例1</h3>
        <input type="button" class="btn btn-primary" value="点击" onclick="clickMe()"/>
    </div>
{% endblock %}

{% block js %}
    <script type="text/javascript">
        function clickMe() {
            $.ajax({
                url: '/task/ajax/',
                type: "post",
                data: {
                    n1: 123,
                    n2: 456
                },
                success: function (res) {
                    console.log(res);
                }
            })
        }
    </script>
{% endblock %}

Ajax请求的返回值

一般是json格式

转数据格式,转为json格式的数据提供给前端

import json

复制代码
data_dict = {"status": True, "data": [11, 22, 33, 44]}
json.dumps(data_dict)

Django内部转json格式的方法

复制代码
from django.http import JsonResponse
复制代码
def task_ajax(request):
    data_dict = {"status": True, "data": [11, 22, 33, 44]}
    return JsonResponse(data_dict)

使用Ajax发送post请求

task.py文件

python 复制代码
import json
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

def task_list(request):
    """ 任务列表 """
    return render(request, "task_list.html")


@csrf_exempt
def task_ajax(request):
    data_dict = {"status": True, "data": [11, 22, 33, 44]}
    return HttpResponse(json.dumps(data_dict))
    # return JsonResponse(data_dict)

task_list.html

html 复制代码
{% extends 'layout.html' %}

{% block content %}
    <div class="container">
        <h1>任务管理</h1>

        <h3>示例1</h3>
        <input type="button" class="btn btn-primary" value="点击" id="btn1"/>
    </div>
{% endblock %}

{% block js %}
    <script type="text/javascript">
        $(function() {
            //页面框架加载完成之后代码自动执行
            bindBtn1Event();
        })

        function bindBtn1Event() {
            $("#btn1").click(function () {
                $.ajax({
                    url: '/task/ajax/',
                    type: "post",
                    data: {
                        n1: 123,
                        n2: 456
                    },
                    dataType: "JSON",
                    success: function (res) {
                        console.log(res);
                        console.log(res.status);
                        console.log(res.data);
                    }
                })
            })
        }
    </script>
{% endblock %}

把表单中所有数据打包使用Ajax发送,是get请求的话使用request.GET就可以拿到前端传过来的数据

运行创建数据库代码的命令语句

python 复制代码
 python manage.py makemigrations
python 复制代码
 python manage.py migrate 

定义数据库格式的时候页面会自动展示长文本格式

如果不需要的话可以这么写

也可以这么写

使用ajax实现form表单数据的提交与保存到数据库

task.py

python 复制代码
import json

from django import forms
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from app01.utils.bootstrap import BootStrapModelForm
from app01 import models


class TaskModelForm(BootStrapModelForm):
    class Meta:
        model = models.Task
        fields = "__all__"
        widgets = {
            # "detail": forms.Textarea
            "detail": forms.TextInput
        }


def task_list(request):
    """ 任务列表 """
    form = TaskModelForm()
    return render(request, "task_list.html", {"form": form})


@csrf_exempt
def task_ajax(request):
    print(request.POST)
    data_dict = {"status": True, "data": [11, 22, 33, 44]}
    return HttpResponse(json.dumps(data_dict))
    # return JsonResponse(data_dict)


@csrf_exempt
def task_add(request):
    # 用户发送过来的数据进行校验(ModelForm进行校验)
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {"status": True}
        return HttpResponse(json.dumps(data_dict))

    data_dict = {"status": True, 'error': form.errors}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))

task_list.html

html 复制代码
{% extends 'layout.html' %}

{% block content %}
<div class="container">
    <div class="panel panel-default">
        <div class="panel-heading">表单</div>
        <div class="panel-body">
            <form id="formAdd">
                <div class="clearfix">
                    {% for field in form %}
                        <div class="col-xs-6">
                            <div class="form-group" style="position: relative;margin-bottom: 20px;">
                                <label>{{ field.label }}</label>
                                {{ field }}
                                <span class="error-msg" style="color: red; position: absolute"></span>
                            </div>
                        </div>
                    {% endfor %}
                    <div class="col-xs-12">
                        <button id="btnAdd" type="button" class="btn btn-primary">提 交</button>
                    </div>
                </div>

            </form>
        </div>
    </div>

    <h1>任务管理</h1>

    <h3>示例1</h3>
    <input type="button" class="btn btn-primary" value="点击" id="btn1"/>

    <h3>示例2</h3>
    <input type="text" id="txtUser" placeholder="姓名"/>
    <input type="text" id="txtAge" placeholder="年龄"/>
    <input type="button" class="btn btn-primary" value="点击2" id="btn2"/>

    <h3>示例3</h3>
    <form id="form3">
        <input type="text" name="user" placeholder="姓名">
        <input type="text" name="age" placeholder="年龄">
        <input type="text" name="email" placeholder="邮箱">
        <input type="text" name="more" placeholder="介绍">
    </form>
    <input type="button" class="btn btn-primary" value="点击3" id="btn3"/>
</div>
{% endblock %}

{% block js %}
<script type="text/javascript">
    $(function() {
        //页面框架加载完成之后代码自动执行
        bindBtn1Event();
        bindBtn2Event();
        bindBtn3Event();
        bindBtnAddEvent();
    })

    function bindBtn1Event() {
        $("#btn1").click(function () {
            $.ajax({
                url: '/task/ajax/',
                type: "post",
                data: {
                    n1: 123,
                    n2: 456
                },
                dataType: "JSON",
                success: function (res) {
                    console.log(res);
                    console.log(res.status);
                    console.log(res.data);
                }
            })
        })
    }

    function bindBtn2Event() {
         $("#btn2").click(function () {
            $.ajax({
                url: '/task/ajax/',
                type: "post",
                data: {
                    name: $("#txtUser").val(),
                    age: $("#txtAge").val(),
                },
                dataType: "JSON",
                success: function (res) {
                    console.log(res);
                    console.log(res.status);
                    console.log(res.data);
                }
            })
        })
    }

    function bindBtn3Event() {
         $("#btn3").click(function () {
            $.ajax({
                url: '/task/ajax/',
                type: "post",
                data: $("#form3").serialize(),
                dataType: "JSON",
                success: function (res) {
                    console.log(res);
                    console.log(res.status);
                    console.log(res.data);
                }
            })
        })
    }

    function bindBtnAddEvent() {
         $("#btnAdd").click(function () {
            $("#error-msg").empty();
            $.ajax({
                url: '/task/add/',
                type: "post",
                data: $("#formAdd").serialize(),
                dataType: "JSON",
                success: function (res) {
                    if(res.status){
                        alert("添加成功");
                    } else {
                        $.each(res.error, function (name, data){
                            console.log(name, data);
                            $("#id_" + name).next().text(data[0]);
                        })
                    }
                }
            })
        })
    }
</script>
{% endblock %}

models.py

python 复制代码
from django.db import models


class Admin(models.Model):
    """ 管理员 """
    username = models.CharField(verbose_name="用户名", max_length=32)
    password = models.CharField(verbose_name="密码", max_length=64)

    def __str__(self):
        return self.username


# Create your models here.
class Department(models.Model):
    """ 部门表 """
    title = models.CharField(verbose_name='标题', max_length=32)

    def __str__(self):
        return self.title


class UserInfo(models.Model):
    """ 员工表 """
    name = models.CharField(verbose_name="姓名", max_length=16)
    password = models.CharField(verbose_name="密码", max_length=64)
    age = models.IntegerField(verbose_name="年龄")
    account = models.DecimalField(verbose_name="账户余额", max_digits=10, decimal_places=2, default=0)
    # 包含年月日,时分秒
    # create_time = models.DateTimeField(verbose_name="入职时间")
    # 不包含时分秒
    create_time = models.DateTimeField(verbose_name="入职时间")

    # 无约束
    # depart_id = models.BigIntegerField(verbose_name="部门ID")

    # 1.有约束
    # -to, 与哪张表关联
    # -to_field, 表中的哪一列关联
    # 2.django自动
    # -写的depart
    # -生成数据列depart_id
    # 3.部门表被删除
    # 3.1 级联删除
    depart = models.ForeignKey(to="Department", to_field="id", on_delete=models.CASCADE)
    # 3.2 置空
    # depart = models.ForeignKey(to="Department", to_field="id", null=True, blank=True, on_delete=models.SET_NULL)

    # 在django中做的约束
    gender_choices = (
        (1, "男"),
        (2, "女"),
    )
    gender = models.SmallIntegerField(verbose_name="性别", choices=gender_choices)


class PrettyNum(models.Model):
    """ 靓号表 """
    mobile = models.CharField(verbose_name="手机号", max_length=11)
    # 想要允许为空 null=True, blank=True
    price = models.IntegerField(verbose_name="价格", default=0)

    level_choices = (
        (1, "1级"),
        (2, "2级"),
        (3, "3级"),
        (4, "4级"),
    )
    level = models.SmallIntegerField(verbose_name="级别", choices=level_choices, default=1)

    status_choices = (
        (1, "已占用"),
        (2, "未使用"),
    )
    status = models.SmallIntegerField(verbose_name="状态", choices=status_choices, default=2)


class Task(models.Model):
    """ 任务 """
    level_choices = {
        (1, "紧急"),
        (2, "重要"),
        (3, "临时"),
    }
    level = models.SmallIntegerField(verbose_name="级别", choices=level_choices, default=1)
    title = models.CharField(verbose_name="标题", max_length=64)
    detail = models.TextField(verbose_name="详细信息")
    user = models.ForeignKey(verbose_name="负责人", to="Admin", on_delete=models.CASCADE)

知识点回顾

实现页面的自动刷新更新数据功能

文件命名冲突问题

改为order1.py解决冲突

两种显示模态框的方式

清空错误信息

根据不同登录的用户设置不同的id

出现500的错误

没有登录,使用管理员账户登录一下

实现删除模态框

order_list.html页面

html 复制代码
{% extends 'layout.html' %}

{% block content %}
<div class="container">
    <div style="margin-bottom: 10px">
        <input type="button" value="新建订单1" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
        <input id="btnAdd" type="button" value="新建订单2" class="btn btn-primary">
    </div>

    <div class="panel panel-default">
        <!-- Default panel contents -->
        <div class="panel-heading">
            <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
            订单列表
        </div>

        <!-- Table -->
        <table class="table table-bordered">
            <thead>
            <tr>
                <th>ID</th>
                <th>订单号</th>
                <th>名称</th>
                <th>价格</th>
                <th>状态</th>
                <th>管理员</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {% for obj in queryset %}
            <tr>
                <th>{{ obj.id }}</th>
                <td>{{ obj.oid }}</td>
                <td>{{ obj.title }}</td>
                <td>{{ obj.price }}</td>
                <td>{{ obj.get_status_display }}</td>
                <td>{{ obj.admin.username }}</td>
                <td>
                    <a class="btn btn-primary btn-xs" href="/admin/{{ obj.id }}/edit/">编辑</a>
                    <input class="btn btn-danger btn-xs btn-delete" type="button" value="删除">
                </td>
            </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
    <div class="clearfix">
        <ul class="pagination" style="float:left;">
            {{ page_string }}
        </ul>
    </div>
</div>

<!-- 新建订单(对话框) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">新建</h4>
            </div>
            <div class="modal-body">
                <form id="formAdd">
                    <div class="clearfix">
                        {% for field in form %}
                        <div class="col-xs-6">
                            <div class="form-group" style="position: relative;margin-bottom: 20px;">
                                <label>{{ field.label }}</label>
                                {{ field }}
                                <span class="error-msg" style="color: red; position: absolute"></span>
                            </div>
                        </div>
                        {% endfor %}

                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
                <button id="btnSave" type="button" class="btn btn-primary">保 存</button>
            </div>
        </div>
    </div>
</div>

<!--删除-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="alert alert-danger alert-dismissible fade in" role="alert">
            <h4>是否确定删除?</h4>
            <p style="margin: 10px 0;">删除后可能会出现不一样的问题</p>
            <p style="text-align: right;">
                <button type="button" class="btn btn-danger">确 定</button>
                <button type="button" class="btn btn-default">取 消</button>
            </p>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script type="text/javascript">
    $(function () {
        bindBtnAddEvent();
        bindBtnSaveEvent();
        bindBtnDeleteEvent();
    })

    function bindBtnAddEvent() {
        $("#btnAdd").click(function () {
            console.log(123);
            //点击新建按钮,显示对话框
            $('#myModal').modal('show')
        });
    }

    function bindBtnSaveEvent() {
        $("#btnSave").click(function() {
            // 清除错误信息
            $("#error-msg").empty();
            // 向后台发送请求
            $.ajax({
                url: "/order/add/",
                type: "post",
                data: $("#formAdd").serialize(),
                dataType: "JSON",
                success: function (res) {
                    if(res.status) {
                        alert("创建成功");
                        // 清空表单
                        $("#formAdd")[0].reset();

                        //关闭对话框
                        $('#myModal').modal('hide');
                        location.reload();
                    } else {
                        $.each(res.error, function (name, errorList) {
                            $("#id_" + name).next().text(errorList[0]);
                        })
                    }
                }
            });
        });
    }

    function bindBtnDeleteEvent() {
        $(".btn-delete").click(function() {
            $("#deleteModal").modal('show');
        });
    }
</script>
{% endblock %}

order1.py

python 复制代码
import json
import random

from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from app01 import models
from app01.utils.bootstrap import BootStrapModelForm
from django.views.decorators.csrf import csrf_exempt
from datetime import datetime
from app01.utils.pagination import Pagination

class OrderModelForm(BootStrapModelForm):
    class Meta:
        model = models.Order
        # field = "__all__"
        # fields = [""]
        exclude = ["oid", "admin"]


def order_list(request):
    queryset = models.Order.objects.all().order_by('-id')
    page_object = Pagination(request, queryset)
    form = OrderModelForm()

    context = {
        'form': form,
        'queryset': page_object.page_queryset,
        'page_string': page_object.html()
    }
    return render(request, 'order_list.html', context)


@csrf_exempt
def order_add(request):
    """ 新建订单 (Ajax请求)"""
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        # 额外增加一些不是用户输入的值(自己计算值)
        form.instance.oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000, 9999))

        # 固定设置管理员ID
        # form.instance.admin = 当前登录系统管理员的ID
        # keys = list(request.session.keys())
        # print(keys)
        form.instance.admin_id = request.session["info"]["id"]
        # 保存到数据库中
        form.save()
        return JsonResponse({"status": True})
        # return HttpResponse(json.dumps({"status": True}))

    return JsonResponse({"status": False, 'error':  form.errors})
相关推荐
王夏奇2 分钟前
C代码—单元测试中的覆盖率—学习笔记
笔记·学习·单元测试
雷神乐乐8 分钟前
Flume学习
hadoop·学习·flume
向上的车轮13 分钟前
ODOO学习笔记(8):模块化架构的优势
笔记·python·学习·架构
HC182580858322 小时前
“倒时差”用英语怎么说?生活英语口语学习柯桥外语培训
学习·生活
学习路上_write2 小时前
FPGA/Verilog,Quartus环境下if-else语句和case语句RT视图对比/学习记录
单片机·嵌入式硬件·qt·学习·fpga开发·github·硬件工程
非概念2 小时前
stm32学习笔记----51单片机和stm32单片机的区别
笔记·stm32·单片机·学习·51单片机
无敌最俊朗@3 小时前
stm32学习之路——八种GPIO口工作模式
c语言·stm32·单片机·学习
EterNity_TiMe_3 小时前
【论文复现】STM32设计的物联网智能鱼缸
stm32·单片机·嵌入式硬件·物联网·学习·性能优化
L_cl4 小时前
Python学习从0到1 day28 Python 高阶技巧 ⑤ 多线程
学习
前端SkyRain4 小时前
后端Node学习项目-用户管理-增删改查
后端·学习·node.js