How do I overwrite the file if the name of the new file is similar to the one already uploaded. If I can take file.name and delete any file present with this name and then store this file that also works for any . Any method would work please help This is my view.py
from django.shortcuts import render
from django.views.generic import TemplateView
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse
import requests
from geopy.distance import geodesic as GD
import pandas as pd
from subprocess import run,PIPE
from .forms import UploadFileForm
from django.core.files.storage import FileSystemStorage
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
file = request.FILES['file']
fs = FileSystemStorage()
fs.save(file.name, file)
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form':form})
As you mentioned, removing an existed file with the current file name is ok for you, you can use this:
import os
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
file = request.FILES['file']
name = str(file.name).replace("\\", "/")
if os.path.exists(name):
os.remove(name)
fs = FileSystemStorage()
fs.save(file.name, file)
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form':form})
Also, you can rename the old file (by adding rename time to end of the original name) and save the new file by its name:
import os
from datetime import datetime
def content_file_name(filename):
file_root, file_ext = os.path.splitext(filename)
return f'{file_root}_{datetime.utcnow().time()}{file_ext}'
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
file = request.FILES['file']
name = str(file.name).replace("\\", "/")
if os.path.exists(name):
os.rename(src=name, dst=content_file_name(name))
fs = FileSystemStorage()
fs.save(file.name, file)
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form':form})
Also, you can save each file with its uploaded time in its name:
import os
from datetime import datetime
def content_file_name(filename):
file_root, file_ext = os.path.splitext(filename)
return f'{file_root}_{datetime.utcnow().time()}{file_ext}'
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
file = request.FILES['file']
file.name = content_file_name(file.name)
fs = FileSystemStorage()
fs.save(file.name, file)
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form':form})