In the previous tutorial, you learned how to upload a file and how Django manipulates file names automatically. However, in some situations you may also need to change the filename yourself before Django saves it. For example, you may wish to append the name of the person as a prefix to the filename. Here, you will see how.
Modify file2local/resume/models.py as follows:
Add a new function ownerpics and change
owner_pic=models.ImageField(upload_to = 'ownerpics')
to
owner_pic=models.ImageField(upload_to = ownerpics)
instance
---------------------------------code---------------------------------------------------
Add a new function ownerpics and change
owner_pic=models.ImageField(upload_to = 'ownerpics')
to
owner_pic=models.ImageField(upload_to = ownerpics)
Note the absence of the quotes around ownerpics. The Django doc says that, the upload_to value 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.
---------------------------------code---------------------------------------------------
def ownerpics(instance,filename):
prefix = instance.owner_name.replace(' ','_')
newfilename = prefix + '_' + filename
return "ownerpics/" + newfilename
class Resume(models.Model):
owner_name=models.CharField(max_length=40)
owner_pic=models.ImageField(upload_to = ownerpics)
prefix = instance.owner_name.replace(' ','_')
newfilename = prefix + '_' + filename
return "ownerpics/" + newfilename
class Resume(models.Model):
owner_name=models.CharField(max_length=40)
owner_pic=models.ImageField(upload_to = ownerpics)
Now, let's fill up the form and submit again.
On successful submission, you will find an entry in the database table as,
Note the name of the file. Originally it was photo.jpeg. After upload it got renamed to Isaac_Newton_photo.jpeg where Isaac Newton is the name of the owner.
No comments:
Post a Comment