How to change the file name of an uploaded file in Django? - python

Is it possible to change the file name of an uploaded file in django? I searched, but couldn't find any answer.
My requirement is whenever a file is uploaded its file name should be changed in the following format.
format = userid + transaction_uuid + file_extension
Thank you very much...

How are you uploading the file?
I assume with the FileField.
The documentation for FileField.upload_to says that the upload_to field,
may also be a callable, such as a
function, which will be called to
obtain the upload path, including the
filename. This callable must be able
to accept two arguments, and return a
Unix-style path (with forward slashes)
to be passed along to the storage
system. The two arguments that will be
passed are:
"instance": An instance of
the model where the FileField is
defined. More specifically, this is
the particular instance where the
current file is being attached.
"filename":The filename that was
originally given to the file. This may
or may not be taken into account when
determining the final destination
path.
So it looks like you just need to make a function to do your name handling and return the path.
def update_filename(instance, filename):
path = "upload/path/"
format = instance.userid + instance.transaction_uuid + instance.file_extension
return os.path.join(path, format)

You need to have a FileField with the upload_to that calls to a callback, see [1]
Your callback should call a wrapper method which gets an instance as one of the params and filename as the other. [2]
Change it the way you like and return the new path [3]
1. LOGIC
FileField(..., upload_to=method_call(params),....)
2. define method
def method_call(params):
return u'abc'
3. Wrapper:
def wrapper(instance, filename):
return method
this is the rapper method that you need for getting the instance.
def wrapper(instance, filename):
... Your logic
...
return wrapper
Complete Code
def path_and_rename(path, prefix):
def wrapper(instance, filename):
ext = filename.split('.')[-1]
project = "pid_%s" % (instance.project.id,)
# get filename
if instance.pk:
complaint_id = "cid_%s" % (instance.pk,)
filename = '{}.{}.{}.{}'.format(prefix, project, complaint_id, ext)
else:
# set filename as random string
random_id = "rid_%s" % (uuid4().hex,)
filename = '{}.{}.{}.{}'.format(prefix, project, random_id, ext)
# return the whole path to the file
return os.path.join(path, filename)
return wrapper
Call to Method
sales_attach = models.FileField("Attachment", upload_to=path_and_rename("complaint_files", 'sales'), max_length=500,
help_text="Browse a file")
Hope this helps.
Thanks.

if you want your function re-usable:
import hashlib
import datetime
import os
from functools import partial
def _update_filename(instance, filename, path):
path = path
filename = "..."
return os.path.join(path, filename)
def upload_to(path):
return partial(_update_filename, path=path)
You just have to use it this way:
document = models.FileField(upload_to=upload_to("my/path"))

import random
import os
def generate_unique_name(path):
def wrapper(instance, filename):
extension = "." + filename.split('.')[-1]
filename = str(random.randint(10,99)) + str(random.randint(10,99)) + str(random.randint(10,99)) + str(random.randint(10,99)) + extension
return os.path.join(path, filename)
return wrapper
#You just have to use it this way:#
photo = models.FileField("Attachment", upload_to=generate_unique_name("pics"),max_length=500,help_text="Browse a photo")

Incase this may help anyone.
import os
import uuid
import random
from datetime import datetime
def user_directory_path(instance, filename):
# Get Current Date
todays_date = datetime.now()
path = "uploads/{}/{}/{}/".format(todays_date.year, todays_date.month, todays_date.day)
extension = "." + filename.split('.')[-1]
stringId = str(uuid.uuid4())
randInt = str(random.randint(10, 99))
# Filename reformat
filename_reformat = stringId + randInt + extension
return os.path.join(path, filename_reformat)
class MyModel(models.Model):
upload = models.FileField(upload_to=user_directory_path)

That much code is not needed you can just use single line code
fille._name=userid + transaction_uuid + file_extension
Like
class xyz(models.Model):
file = models.FileField(upload_to="notice/")
def add(request):
file = request.POST['file']
file._name = request.user.id + transaction_uuid +"."+ file._name.split('.')[1]
you can overwrite file name by overwriting _name value of file object.

The basic way is
import os
os.rename('a.txt', 'b.html')
For your situation, it would probably look like
os.rename ("a.txt", "{id}{uuid}.{ext}".format(id=userid, uuid=transaction_uuid, ext=file_extension))

Hi, i check all the answers, but someone are not updated, this is how
in 2022 works whith clean code and following the Django Documentation
Here, remember that you need to make a MIGRATION to make this work:
def AvatarSave(instance, filename):
#this line changes the name of the file to the user name and put the file extension at the end after the point
return 'users/avatars/{0}.{1}'.format(instance.id,filename.split('.')[-1])
avatar = models.ImageField(_("avatar"),upload_to=AvatarSave)

Related

How to implement a watchdog like in native python?

I have a tool which generates some reports as html file. Since there are many and it need to be generated manual organizing them manually will take a lot of time and that's why I tried on making a script which will organize the files automatically with some rules I have applied.
import os
import re
import endwith
filefullname = EndsWith('.html')
allfiles = filefullname.findfile()
report_path = "/home/user/reports/"
while True:
files = os.listdir("/home/user/")
if not allfiles:
continue
else:
header = re.match(r"^[^_]+(?=_)", allfiles[0])
if not os.path.exists(report_path + str(header.group())):
os.system(f"mkdir {report_path + str(header.group())}")
os.system(f"mv /home/user/*.html reports/{str(header.group())}")
else:
os.system(f"mv /home/user/*.html reports/{str(header.group())}")
This is the main file which do the automation. and the class is a custom endswith class because the native one returned only boolean types. The thing is it that it runs but the problem is that it requires a restart to finish the job.
Any suggestions?
P.S. This is the class code:
import os
class EndsWith:
def __init__(self, extension):
self.extension = extension
def findfile(self):
files = os.listdir("/home/user/")
file_list = []
for file in files:
#print(file)
if self.extension in file:
file_list.append(file)
return file_list

How could I know if I already import a modul and reload it if it has been modified?

I made a class where I have a model in it. I also made a QT GUI which allows me to select the file (.py) of my class model in order to import it and use it.
What I'm seeking for is a way to know if I already import a modul (corresponding to the file I selected) and reload it if it has changed.
to import my module from a path, i use:
fileName = QFileDialog.getOpenFileName(self,"Open Data File" , "", "data files (*.py)")
if fileName[0]=='':
return
fileName = str(fileName[0])
abspath = os.path.dirname(os.path.abspath(__file__))
self.fileName = os.path.relpath(fileName,abspath)
(filepath, filename) = os.path.split(fileName)
sys.path.append(filepath)
(shortname, extension) = os.path.splitext(filename)
mod = __import__(shortname)
instead of mod = __import__(shortname) I need to make a test to know if I import or reload the module.
EDIT
if shortname not in sys.modules:
mod = __import__(shortname)
else:
importlib.reload(__import__(shortname))
I try the previous code. however I still have an issue. when I do importlib.reload(__import__(shortname)), I seem that when I modify the module in between the first import and the second one, I still load the first form of the class. I added self.A=0 in the class __init__ but I don't have the acces to it.

Cant change string value to variable with string value

I upload file to dropbox api, but it post on dropbox all directories from my computer since root folder. I mean you have folder of your project inside folder home, than user until you go to file sours folder. If I cut that structure library can't see that it is file, not string and give mistake message.
My code is:
def upload_file(project_id, filename, dropbox_token):
dbx = dropbox.Dropbox(dropbox_token)
file_path = os.path.abspath(filename)
with open(filename, "rb") as f:
dbx.files_upload(f.read(), file_path, mute=True)
link = dbx.files_get_temporary_link(path=file_path).link
return link
It works, but I need something like:
file_path = os.path.abspath(filename)
chunks = file_path.split("/")
name, dir = chunks[-1], chunks[-2]
which gives me mistake like:
dropbox.exceptions.ApiError: ApiError('433249b1617c031b29c3a7f4f3bf3847', GetTemporaryLinkError('path', LookupError('not_found', None)))
How could I make only parent folder and filename in the path?
For example if I have
/home/user/project/file.txt
I need
/project/file.txt
you have /home/user/project/file.txt and you need /project/file.txt
I would split according to os default separator (so it would work with windows paths as well), then reformat only the 2 last parts with the proper format (sep+path) and join that.
import os
#os.sep = "/" # if you want to test that on Windows
s = "/home/user/project/file.txt"
path_end = "".join(["{}{}".format(os.sep,x) for x in s.split(os.sep)[-2:]])
result:
/project/file.txt
I assume the following code should works:
def upload_file(project_id, filename, dropbox_token):
dbx = dropbox.Dropbox(dropbox_token)
abs_path = os.path.abspath(filename)
directory, file = os.path.split(abs_path)
_, directory = os.path.split(directory)
dropbox_path = os.path.join(directory, file)
with open(abs_path, "rb") as f:
dbx.files_upload(f.read(), dropbox_path, mute=True)
link = dbx.files_get_temporary_link(path=dropbox_path).link
return link

Django dynamic file upload path

Here its my django code.
I want to upload my file on specific location and that path is created dynamically.
def get_upload_file(instance, filename):
today_date = datetime.datetime.today().date()
directory = 'Data/'+ str(today_date)
if not os.path.exists(directory):
os.makedirs(directory)
full_path = str(directory)+"/%s" %(filename)
print "full_path --> ",full_path
# user = updated_path()
# print user
return full_path
class UploadFile(models.Model):
path = models.FileField(upload_to=get_upload_file)
I am trying above code to upload file but i want to another directory in it and its name is on username.
expected output
Data/2015-08-16/username/
then i want to upload file in username directory
any solution please help me
Finally I got a solution for the above problem. When I am creating class instance set request object to that instance and access that request object in get_upload_file function
class UploadFile(models.Model):
path = models.FileField(upload_to=get_upload_file)
reqObj = None
def set_reqObj(self, request):
self.reqObj = request
new_file = UploadFile(path = afile)
new_file.set_reqObj(request)
use reqObj in get_upload_file function
instance.reqObj.user.username
updated get_upload_file function is
def get_upload_file(instance, filename):
today_date = datetime.datetime.today().date()
directory = 'Data/'+ str(today_date)+'/'+instance.reqObj.user.username
if not os.path.exists(directory):
os.makedirs(directory)
full_path = str(directory)+"/%s" %(filename)
return full_path

Getting the current path from where a module is being called

I have a python module I built myself and it's located in /usr/local/lib/python3.4/site-packages/my_module1. In the module I have this:
class Class1(object);
def __init__(self, file_name):
self.file_name = file_name # how can I get the full path of file_name?
How do I get the full of file_name? That is, if it's just a file name without a path, then append the current folder from where the module is being called. Otherwise, treat the file name as a full path.
# /users/me/my_test.py
from module1 import Class1
c = Class1('my_file1.txt') # it should become /users/me/my_file1.txt
c1 = Class1('/some_other_path/my_file1.txt') # it should become /some_other_path/my_file1.txt/users/me/my_file1.txt
Update: Sorry about that. I mis-read your question. All you need to do is pass filename so os.path.abspath().
Example:
import os
filename = os.path.abspath(filename)
To cater for your 2nd case (which I find quite weird):
import os
if os.path.isabs(filenaem):
filename os.path.join(
os.path.join(
filename,
os.getcwd()
),
os.path.basename(filename)
)

Categories