首页 > 解决方案 > 如何防止在提交表单时上传文件

问题描述

我用进度条在 django 中上传文件,当我选择文件时,进度开始,完成时意味着文件上传,但是当我点击提交表单时,文件再次上传,这意味着进度条没用,所以我想做一些事情,当我点击提交按钮时,文件与表单一起保存但不再上传,我该怎么做?

我的表格

class Video_form(forms.ModelForm,):
    class Meta:
        model = Video
        fields = ('video', 'video_poster', 'title',)

风景

def VideosUploadView(request, *args, **kwargs):
V_form = Video_form()
video_added = False

if not request.user.is_active:
    # any error you want
    return render('account/login.html')

try:
    account = Account.objects.get(username=request.user.username)
except:
    # any error you want
    return HttpResponse('User does not exits.')

if 'submit_v_form' in request.POST:
    print(request.POST)
    V_form = Video_form(request.POST, request.FILES)
    if V_form.is_valid():
        instance = V_form.save(commit=False)

        video = request.FILES['video']
        clip = VideoFileClip(video.temporary_file_path())
        instance.video_duration = clip.duration

        instance.author = account
        instance.save()
        V_form.save_m2m()
        V_form = Video_form()
        video_added = True

        if instance.save:
            return redirect('home')
contex = {
    'account': account,
    'V_form': V_form,
    'video_added': video_added,
}


return render(request, "video/upload_videos.html", contex)

模板

<form  id="upload-form" action="." method="post" enctype="multipart/form-data">
                                {% csrf_token %}
                                <div id="progress-box" class="d-none">progress</div>

                                <div class="custom-file">

                                     <input type="file" class="custom-file-input" id="formGroupExampleInput2" required value="{{V_form.video}}">
                                     <label class="custom-file-label" for="formGroupExampleInput2">Choose Video...</label>
                                </div>

                                <div class="custom-file mt-5 mb-4">

                                       <input type="file" class="custom-file-input" id="file2" required value="{{V_form.video_poster}}">
                                     <label class="custom-file-label" for="formGroupExampleInput2">Choose Poster For Your Video...</label>

                                </div>

                                  <div class="d-flex justify-content-center my-3 px-3" >  <button class="btn-block btnn-color" name="submit_v_form"> Upload</button></div>
                          </form>

标签: djangodjango-modelsdjango-viewsdjango-formsdjango-templates

解决方案


推荐阅读