Django学习第五天

 启动项目命令

python manage.py runserver

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

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

{% 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

{% 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文件

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

{% 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 manage.py makemigrations
 python manage.py migrate 

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

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

也可以这么写

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

task.py

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

{% 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

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页面

{% 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

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})

相关推荐

  1. 56django学习

    2024-07-09 16:48:14       39 阅读
  2. 回顾Django

    2024-07-09 16:48:14       39 阅读
  3. 开始学习

    2024-07-09 16:48:14       38 阅读
  4. 58django学习(七)

    2024-07-09 16:48:14       37 阅读
  5. 57django学习(六)

    2024-07-09 16:48:14       33 阅读
  6. 59django学习(八)

    2024-07-09 16:48:14       36 阅读
  7. 63-django学习(十二)

    2024-07-09 16:48:14       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-09 16:48:14       3 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-09 16:48:14       3 阅读
  3. 在Django里面运行非项目文件

    2024-07-09 16:48:14       2 阅读
  4. Python语言-面向对象

    2024-07-09 16:48:14       2 阅读

热门阅读

  1. CSS里的几个小知识

    2024-07-09 16:48:14       12 阅读
  2. 社交媒体原生应用开发:Facebook的创新之路

    2024-07-09 16:48:14       12 阅读
  3. Gunicorn+Flask+Docker初体验

    2024-07-09 16:48:14       10 阅读
  4. 常用目标检测的格式转换脚本文件txt,json等

    2024-07-09 16:48:14       12 阅读
  5. 信息收集-arping

    2024-07-09 16:48:14       10 阅读
  6. flutter如何实现点击一文字后 打开对应的超链接

    2024-07-09 16:48:14       10 阅读
  7. TCP协议是安全的吗?

    2024-07-09 16:48:14       25 阅读
  8. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-07-09 16:48:14       26 阅读
  9. 【Python教程】压缩PDF文件大小

    2024-07-09 16:48:14       27 阅读
  10. 通过文章id递归查询所有评论(xml)

    2024-07-09 16:48:14       32 阅读