DropZone的使用

 本节内容:

1:dropzone的使用

 

写的好的:https://www.cnblogs.com/webenh/p/6143237.html

官网:http://www.dropzonejs.com/

GitHub:https://github.com/enyo/dropzone

 

html:

{% extends "index.html" %}


{% block extra-css %}
    <link rel="stylesheet" href="/static/plugins/dropzone/dropzone.css" type="text/css">
    <style>
        .dropzone {
            border: 2px dashed #0087F7;
            border-radius: 5px;
            background: white;
        }
    </style>
{% endblock %}

{% block body %}

    <div class="container">
        <h3>老男孩教育|IT学员报名</h3>
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h3 class="panel-title">学员在线报名</h3>
            </div>
            <div class="panel-body">

                <form class="form-horizontal" method="post" onsubmit="return BeforeSubmit(this)">
                    {% csrf_token %}
                    {% for field in form_obj %}
                        <div class="form-group col-lg-6">
                            <label for="inputEmail3" class="col-sm-2 control-label">{{ field.label }}</label>
                            <div class="col-sm-10">
                                {{ field }}
                                <span style="color: red">{{ field.errors.0 }}</span>
                            </div>
                        </div>
                    {% endfor %}


                    <div class="form-group col-lg-6">
                        <label for="inputEmail3" class="col-sm-2 control-label">报名班级</label>
                        <div class="col-sm-10">
                            <p>{{ enrollment_obj.class_grade }}</p>
                        </div>
                    </div>

                    <div class="form-group col-lg-6">
                        <label for="inputEmail3" class="col-sm-2 control-label">学费</label>
                        <div class="col-sm-10">
                            <p>{{ enrollment_obj.class_grade.course.price }}</p>

                        </div>
                    </div>


                    <div class="form-group col-lg-12">
                        <hr>
                        <pre style="height: 400px;">{{ enrollment_obj.class_grade.contract_template.content }}</pre>
                        <input type="checkbox" name="contract_agreed">我已认真阅读,无条件同意。
                    </div>


                    <div class="col-lg-12 col-lg-offset-11 col-sm-1">
                        <button type="submit" class="btn btn-info">提交</button>
                    </div>
                </form>

                <div class="form-group col-lg-12">

                    <hr>
                    <span>已上传文件</span>
                    <ul id="uploaded_files">
                        {% for ii in upload_files %}
                            <li>{{ ii }}</li>
                        {% endfor %}
                    </ul>
                    <!-- action 就是他上传的地址 默认是post方式-->
                    <form action="{% url 'enrollment_fileupload' enrollment_obj.id %}" class="dropzone"
                          id="myAwesomeDropzone">
                        <div class="fallback">
                            <input name="file" type="file" multiple/>
                        </div>
                    </form>
                </div>

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







{% endblock %}



{% block extra-js %}
<script src="/static/plugins/dropzone/dropzone.js"></script>
    <script>


        function BeforeSubmit(ele) {
            $("[disabled=true]").each(function () {
                $(this).prop("disabled", false)
            });

               if ($("#uploaded_files").children().length ==0){
                alert("请上传个人证件信息!");
                return false
            };

            if (!$("input[name='contract_agreed']").prop("checked")){
                alert("必须勾选仙剑奇侠传合同协议");
                return false
            };

            return true
        }

        //myAwesomeDropzone 就是form的id,这就是他的配置
        Dropzone.options.myAwesomeDropzone = {
            paramName: "file", // The name that will be used to transfer the file
            maxFilesize: 1, // MB
            accept: function (file, done) {
                if (file.name == "justinbieber.jpg") {
                    done("Naha, you don't.");
                }
                else {
                    done();
                }
            }
        };

        //这个是方法重写的,
{#        $(function () {#}
{#             Dropzone.options.myAwesomeDropzone = false;//下面的代码会new一个新的会报错,使用这个不再创建一个新的对象#}
{#            var myDropzone = new Dropzone("#myAwesomeDropzone"); //html的标签id#}
{#            myDropzone.on("completet", function (file) {        //complete是上传成功或者失败的时候执行,只有一个参数#}
{#                console.log(file);#}
{#                   #}
{##}
{#            });#}
{#        });#}

                 $(function() {
                     Dropzone.options.myAwesomeDropzone = false;
                     var myDropzone = new Dropzone("#myAwesomeDropzone");
                     myDropzone.on("success", function (file, response) {
                         console.log(file.name,response)
                         var response = JSON.parse(response);
                         if (!response.status) {
                             alert(response.err_msg);
                         } else {
                             $("#uploaded_files").append("<li>" + file.name + "</li>");

                         }

                     });
                 })




    </script>
{% endblock %}
View Code

views:

返回已有的文件列表:

###学员报名
def enrollment(request,enrollment_id):
    """学员报名地址"""
    enrollment_obj = models.StudentEnrollment.objects.filter(id=enrollment_id)[0]
    ##当用户填写完报名表后再进行url进行填写的时候,直接返回页面
    if enrollment_obj.contract_approved:
        return HttpResponse("审核通过,欢迎加入老男孩教育,请联系班主任拿取,账号密码。")
    elif enrollment_obj.contract_agreed:
        return HttpResponse("你已成功提交报名信息,请等待审核,欢迎加入老男孩教育")
    if request.method == "POST":
        form_obj = forms.CustomerForm(instance=enrollment_obj.customer,data=request.POST)
        if form_obj.is_valid():
            form_obj.save()
            ##用户填写信息后要进行用户同意和签署时间
            enrollment_obj.contract_agreed = True
            #from django.utils.timezone import datetime  默认的datetime模块是不带时区的
            enrollment_obj.contract_signed_date = timezone.now()
            enrollment_obj.save()
            return HttpResponse("你已成功提交报名信息,请等待审核,欢迎加入老男孩教育")
    else:
        form_obj = forms.CustomerForm(instance=enrollment_obj.customer)
        # 列出学员已上传的文件
        upload_files = []
        enrollment_upload_dir = os.path.join(settings.CRM_file_upload, enrollment_id)
        if os.path.isdir(enrollment_upload_dir):
            upload_files = os.listdir(enrollment_upload_dir)

    return render(request,"crm/enrollment.html",locals())

接受上传文件:

###报名上传视图
@csrf_exempt
def enrollment_file(request,enrollment_id):
    """用户上传文件"""
    enrollment_file_dir = os.path.join(settings.CRM_file_upload,enrollment_id)
    if not os.path.isdir(enrollment_file_dir):
        os.makedirs(enrollment_file_dir)
    file_obj = request.FILES.get("file")
    file_name = file_obj.name
    file_path = os.path.join(enrollment_file_dir, file_name)
    if len(os.listdir(enrollment_file_dir)) <3:
        with open(file_path,"wb") as f :
            for line in file_obj.chunks():
                f.write(line)
    else:
        return HttpResponse(json.dumps({"status":False,"err_msg":"最多只能存三个文件"}))
    return HttpResponse(json.dumps({'status': True, }), )

 

posted @ 2018-05-26 17:48  你是我的神奇  阅读(1399)  评论(0编辑  收藏  举报