I'm trying to save images that are given from link, such a way that, image save in the given path and image file_name is created with uuid
like below:
my profile model is:
class Profile(DataTimeModel):
first_name = models.CharField(max_length=100)
middle_name = models.CharField(max_length=100, null=True, blank=True)
last_name = models.CharField(max_length=100)
email_address = models.CharField(max_length=100)
phone_number = models.CharField(max_length=100)
address = models.CharField(max_length = 255, null=True, blank=True)
citizenship_no = models.CharField(max_length = 25, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
Now when the profile is enrolled I will send multiple image link or single, from these link I need to download the image and save to the file path like below:
root_dir = MEDIA_ROOT '/profile/'
new_dir = str(profile.id)
file_name = str(uuid.uuid4()) '.jpeg'
path = os.path.join(root_dir, new_dir)
os.makedirs(path)
Now, I need to save the image that comes from the URL into the path
folder with image name file_name
with extension. How can I do that?
I try by using
urllib.request.urlretrieve(url, file_name)
this but it saves into base directory but I need to save in given path.
Image link is given from this interface:
CodePudding user response:
Even if the parameter in urlretrieve is called filename
, you may actually pass in a file path:
Simply combine your path
and file_name
:
path = os.path.join(root_dir, new_dir)
os.makedirs(path)
file_name = str(uuid.uuid4()) '.jpeg'
file_path = os.path.join(path, file_name)
urllib.request.urlretrieve(url, file_path)