django save image in zip

Question:

Client upload zip.

Picture after decompression.

I want to save the picture to the specified location.

But my code cannot be saved to the specified location

How to do?

models.py

def get_upload_path(instance, filename):
    return f'register/{instance.owner.job_number}/{filename}'

class UserRegister(models.Model):
    owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    image = models.ImageField(upload_to=get_upload_path)

    class Meta:
        db_table = 'UserRegister'

views

class AddsUser(View):
    def get(self, request):
        data = {
            'title': 'AddsUser'
        }
        return render(request, './User/adds_user.html', data)

    def post(self, request):
        job_number = request.POST.get('job_number')
        zip_file = request.FILES.get('zip')
        date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        dir_name = uuid.uuid4().hex
        zip_dir_path = f'./temp_zip/{dir_name}'

       # Save zip.
        with open(f'{zip_dir_path}.zip', 'wb') as files: 
            for i in zip_file.chunks():
                files.write(i)
                files.flush()

        os.mkdir(zip_dir_path) # Create folder.
        os.system(f'unzip {zip_dir_path}.zip -d {zip_dir_path}') # unzip

        # Read all pictures in the folder.
        for image_name in os.listdir(zip_dir_path):
            image_path = f"{zip_dir_path}/{image_name}"
            user_profile = UserProfile.objects.create(job_number=job_number, date=date)
            user_register = UserRegister.objects.create(owner_id=user_profile.id,
                                                        image=image_path)
        return redirect(reverse('admin:adds_user'))

This method will not store the picture in the location I specified.

Now database:

./temp_zip/4b9811b0a3c5429cb320cec1357c1099/247688.jpg

I hope the result is:

f'register/{instance.owner.job_number}/{filename}'
register/123/247688.jpg'
Asked By: dudulu

||

Answers:

user_register = UserRegister.objects.create(owner_id=user_profile.id,
                                            image=image_path)

change to

with open(image_path, 'rb') as image_file:
    user_register = UserRegister()
    user_register.owner_id = user_profile.id
    user_register.image.save(image_name, ContentFile(image_file.read()))

This will save the image specification to get_upload_path.

Answered By: dudulu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.