美文网首页
python3 Django layui 表单和文件图片同时上传

python3 Django layui 表单和文件图片同时上传

作者: Xmaxdev | 来源:发表于2019-06-20 19:27 被阅读0次

    继承的base.html 在上一篇文章
    重新输入密码那块很简单就不写了
    话不多说,开始-->

    test.html

    {% extends 'base.html' %}
    {% load static from staticfiles %}
    {% block styles %}
        <style>
            .imgbos {
                width: 200px;
                height: 200px;
                border: 3px solid #0099CC;
                border-radius: 5px;
                padding: 3px;
                text-align: center;
                display: flex;
                align-items: center
            }
    
            .imgbos img {
                max-width: 200px;
                max-height: 200px;
                margin: auto
            }
        </style>
    {% endblock %}
    
    
    {% block body %}
        <div style="margin:10px 20px 0px 10px;height: 475px;overflow:auto;">
            <div class="layui-form">
                <!-- 提示:如果你不想用form,你可以换成div等任何一个普通元素 -->
    
                {% csrf_token %}{# 随机码 #}
                <div class="layui-form-item" id="role">
                    <label class="layui-form-label">角色 <i style="color:red">*</i></label>
                    <div class="layui-input-block">
                        <select name="role" lay-verify="required">
                            {% for i in role_list.data %}
                                <option value="{{ i.role_id }}">{{ i.role_name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名称 <i style="color:red">*</i></label>
                    <div class="layui-input-block">
                        <input type="text" name="user_full_name" lay-verify="required|user_name"
                               placeholder="请输入名称"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">账号 <i style="color:red">*</i></label>
                    <div class="layui-input-block">
                        <input type="text" name="user_name" lay-verify="required|user_name" placeholder="请输入账号"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码 <i style="color:red">*</i></label>
                    <div class="layui-input-block">
                        <input type="password" name="user_password" lay-verify="required|user_password"
                               placeholder="请输入密码"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">重新输入密码 <i style="color:red">*</i></label>
                    <div class="layui-input-block">
                        <input type="password" name="user_password" lay-verify="required|user_password"
                               placeholder="请输入密码"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">邮箱</label>
                    <div class="layui-input-block">
                        <input type="text" name="user_email" lay-verify="email" placeholder="请输入邮箱"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">性别 <i style="color:red">*</i></label>
                    <div class="layui-input-block">
                        <input type="text" name="user_sex" lay-verify="required|required" placeholder="请输入邮箱"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">身份证 <i style="color:red">*</i></label>
                    <div class="layui-input-block">
                        <input type="text" name="user_card" lay-verify="required|identity" placeholder="请输入身份证"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">年龄</label>
                    <div class="layui-input-block">
                        <input type="number" name="user_age" lay-verify="required" placeholder="请输入年龄"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">电话号码 <i style="color:red">*</i></label>
                    <div class="layui-input-block">
                        <input type="text" name="user_phone_number" lay-verify="required|phone"
                               placeholder="请输入电话号码"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">是否有效</label>
                    <div class="layui-input-block">
                        <input type="radio" name="is_active" value="1" title="是"
                               checked="{% if menu_my.menu_type == '1' %}checked{% endif %}">
                        <input type="radio" name="is_active" value="0" title="否"
                               {% if menu_my.menu_type == '0' %}checked{% endif %}>
                    </div>
                </div>
    
                <div class="layui-form-item">
                    <label class="layui-form-label">创建人</label>
                    <div class="layui-input-block">
                        <input type="text" name="createby" lay-verify="required" placeholder="" value="{{ user_id }}"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">更新人</label>
                    <div class="layui-input-block">
                        <input type="text" name="updateby" lay-verify="required" placeholder="" value="{{ user_id }}"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn" id="upload">
                            <i class="layui-icon">&#xe67c;</i>上传图片
                        </button>
                        <br><br>
                        <div class="imgbos">
                            <img id="preview" title="">
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit onclick="" id="commit" lay-filter="*">立即提交</button>
                    </div>
                </div>
            </div>
        </div>
    
    
    {% endblock %}
    {% block scripts %}
        <script>
    
    
            layui.use('element', function (data) {
                var layer = layui.layer;
                var form = layui.form;
                var upload = layui.upload;
                var $ = layui.jquery;
                form.render();//表单渲染
                //表单验证
                form.verify({
                    user_name: function (value, item) { //value:表单的值、item:表单的DOM对象
                        if (!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)) {
                            return '用户名不能有特殊字符';
                        }
                        if (/(^\_)|(\__)|(\_+$)/.test(value)) {
                            return '用户名首尾不能出现下划线\'_\'';
                        }
                        if (/^\d+\d+\d$/.test(value)) {
                            return '用户名不能全为数字';
                        }
                    }, user_password: [
                        /^[\S]{6,12}$/
                        , '密码必须6到12位,且不能出现空格'
                    ]
                });
                //表单提交
                form.on('submit(*)', function (data) {
                    var $ = layui.jquery;
                    if (!$('#preview').attr('src')) {
                        console.log(data.field) //当前容器的全部表单字段,名值对形式:{name: value}
                        //渲染浏览记录
                        $.ajax({
                            type: "POST",
                            url: "{{ path }}/test",
                            data: data.field,
                            dataType: "json",
                            success: function (data) {
                                console.log(1)
                            }
                        });
                        return false; //阻止表单跳转。如果需要表单跳转,去掉这段即可。
                    }
                });
                //upload渲染
                upload.render({
                    elem: '#upload', //上传图标
                    field: 'image',
                    url: '{{ path }}/test',
                    auto: false,//选择文件后不自动上传
                    bindAction: '#commit', //提交按钮
                    size: 20000, //文件大小
                    //上传前的回调
                    before: function (obj) {
                        this.data = {
                            //提交参数
                            role: $(".layui-unselect dd[class='layui-this']").attr('lay-value'),
                            user_full_name: $('input[name="user_full_name"]').val(),
                            user_name: $('input[name="user_name"]').val(),
                            user_password: $('input[name="user_password"]').val(),
                            user_email: $('input[name="user_email"]').val(),
                            user_sex: $('input[name="user_sex"]').val(),
                            user_card: $('input[name="user_card"]').val(),
                            user_age: $('input[name="user_age"]').val(),
                            user_phone_number: $('input[name="user_phone_number"]').val(),
                            is_active: $('input[name="is_active"]').val(),
                            createby: $('input[name="createby"]').val(),
                            updateby: $('input[name="updateby"]').val(),
                            csrfmiddlewaretoken: '{{ csrf_token  }}' //异步提交随机代码
                        }
                    },
                    //选择文件后的回调
                    choose: function (obj) {
                        obj.preview(function (index, file, result) {
                            //生成uuid方法
                            function uuidGenerator() {
                                var originStr = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
                                    originChar = '0123456789abcdef',
                                    len = originChar.length;
                                return originStr.replace(/x/g, function (match) {
                                    return originChar.charAt(Math.floor(Math.random() * len))
                                })
                            }
                            obj.resetFile(index, file, '' + uuidGenerator() + '.jpg'); //图片重命名
                            $('#preview').attr('src', result); //显示上传的图片
                            $('#preview').attr('title', file.name); //鼠标悬停title
                        })
                    },
                    //操作成功的回调
                    done: function (res, index, upload) {
                        var code = res.code === 0 ? 2 : 1;
                        layer.alert('提交成功', {icon: code}, function () {
                            console.log(11111)
                            return false;
                        })
                    },
                    //上传错误回调
                    error: function (res, index, upload) {
                        layer.alert('上传失败!' + res);
                    }
                });
    
            });
    
    
        </script>
    {% endblock %}
    

    setting.py

    MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')  # media即为图片上传的根路径
    MEDIA_URL = '/media/'
    

    views.py

    from django.db.models import Q, Avg, Max, Min, Count, Sum
    from django.http import JsonResponse
    
    @csrf_protect
    def test(request):
        user_id = request.session.get('user_id')
        path = request.scheme + "://" + request.get_host()  # url
        ff_path = request.scheme + "://" + request.get_host() + request.path  # 加方法url
        role_list = {}
        role_list['data'] = list(Role.objects.filter(~Q(role_id=1), is_active=1).values())
        if request.method == 'GET':
            return render(request, "test.html",
                          {'ff_path': ff_path, 'path': path, 'role_list': role_list, 'user_id': user_id})
        else:
            role = request.POST.get('role')
            user_full_name = request.POST.get('user_full_name')
            user_name = request.POST.get('user_name')
            user_password = request.POST.get('user_password')
            user_email = request.POST.get('user_email')
            user_sex = request.POST.get('user_sex')
            user_card = request.POST.get('user_card')
            user_age = request.POST.get('user_age')
            user_phone_number = request.POST.get('user_phone_number')
            is_active = request.POST.get('is_active')
            createby = request.POST.get('createby')
            updateby = request.POST.get('updateby')
            img_url = request.FILES.get('image')
            create_user = User(role_id=role,
                               user_full_name=user_full_name,
                               user_name=user_name,
                               user_password=user_password,
                               user_email=user_email,
                               user_sex=user_sex,
                               user_card=user_card,
                               user_age=user_age,
                               user_phone_number=user_phone_number,
                               is_active=is_active,
                               createby=createby,
                               updateby=updateby,
                               img_url=img_url)
            create_user.save()
            response_data = {"info": "成功更新角色编辑按钮"}
            return JsonResponse(response_data)
    

    models.py

    # 用户
    from django.db import models
    import django.utils.timezone as timezone
    import uuid
    
    class User(models.Model):
        user_id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, editable=False)
        user_full_name = models.CharField('用户名', max_length=30, null=True, blank=True, )
        user_name = models.CharField('账号', max_length=30)
        user_password = models.CharField('密码', max_length=30)
        user_email = models.CharField('邮箱', max_length=45, null=True, blank=True)
        user_sex = models.IntegerField('性别')
        user_age = models.IntegerField('年龄')
        user_phone_number = models.CharField('电话号码', null=True, blank=True, max_length=20, )
        user_card = models.CharField('身份证号码', max_length=30)
        role = models.ForeignKey('Role', on_delete=models.CASCADE)
        createby = models.CharField('创建者', max_length=32)
        createtime = models.DateTimeField('创建时间', default=timezone.now)
        updateby = models.CharField('更新者', max_length=32, null=True)
        updatetime = models.DateTimeField('更新时间', blank=True, null=True)
        is_active = models.IntegerField('是否使用', blank=True, null=True, default=1)
        img_url = models.ImageField('头像', upload_to='img', blank=True, null=True)
    
        class Meta:
            db_table = 'sys_user'
    
        def get_id(self):
            return self.id
    

    urls.py

    from django.urls import path
    from 自己的app名称 import views
    urlpatterns = [
        path('test', views.test),  # 测试页面
    ]
    
    

    数据库结果


    image.png

    上传位置


    image.png

    相关文章

      网友评论

          本文标题:python3 Django layui 表单和文件图片同时上传

          本文链接:https://www.haomeiwen.com/subject/eaxsqctx.html