Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

Uploading duplicated files with Django when reloading page

I'm trying to upload some files and I'm having problems with duplication.

To uploading the file I do the following:

views.py:

from django.core.files.storage import FileSystemStorage

def contView(request):
    if request.method == 'POST' and request.FILES.get('myfile'):
        myfile = request.FILES['myfile']
        fs = FileSystemStorage()
        filename = fs.save('uploads/'+myfile.name, myfile)
        uploaded_file_url = fs.url(filename)
        

    # Return
    template_name ='cont/mainCont.html'
    context = {}
    return render(request, template_name, context)

Template:

<form method="post" enctype="multipart/form-data">{% csrf_token %}
    <div class="input-group">
        <input type="file" name="myfile" class="form-control">
        <span class="input-group-btn">
            <button class="btn btn-default" type="submit">Importar</button>
        </span>
     </div>
</form>

The upload works perfectly but when I refresh the page it upload the same file again. Why is this happening? I need to empty something?

Thank you very much!

question from:https://stackoverflow.com/questions/65925084/uploading-duplicated-files-with-django-when-reloading-page

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is just the standard behaviour of browsers. If you refresh page from a POST request, all of that POST data is sent again. (Although, normally a browser will warn you that this is the case).

If you want to avoid uploading the file twice there are a few approaches you can take:

  1. You can always check to see if that particular file already exists, and not save it again in such cases.
import pathlib
def contView(request):
    if request.method == 'POST' and request.FILES.get('myfile'):
        myfile = request.FILES['myfile']
        if pathlib.Path('uploads/'+myfile.name).is_file():
            # handle file alread uploaded case
            ...
  1. Use the post/redirect/get approach https://en.wikipedia.org/wiki/Post/Redirect/Get
from django.shortcuts import redirect

def contView(request):
    if request.method == 'POST' and request.FILES.get('myfile'):
        ...
        return redirect("some-view or url")

(see https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#redirect)

  1. Maybe submit your data with AJAX. This can be tricky with file uploads though.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...