Home > Blockchain >  What is the easiest way to UPDATE ImageField in Django Rest Framework and delete old image?
What is the easiest way to UPDATE ImageField in Django Rest Framework and delete old image?

Time:01-30

I want to update my image field and delete the old one using the Django-rest framework.

this is my model

class GroupPostsModel(models.Model):
post_text = models.CharField(max_length=1000)
post_type = models.CharField(max_length=20)
image = models.ImageField(blank=True, null=True, upload_to='post_images/')
document = models.FileField(blank=True,null=True, upload_to='post_documents/')
likes = models.IntegerField(default=0)
time_stamp = models.DateTimeField(auto_now=True)
group = models.ForeignKey(GroupsModel, on_delete=models.CASCADE)
user = models.ForeignKey(UserModel, on_delete=models.CASCADE)

class Meta:
    db_table = 'group_posts'

My views.py is as follow

@api_view(['PATCH'])
def save_edited_post_image(request):
image = request.data.get('image')
print('image == ')
print(request.data.get('image'))
post_id = request.data.get('post_id')
print('post id = ' str(post_id))
try:
    GroupPostsModel.objects.filter(id=post_id).update(image=image)
    resp = {
        'resp' : 'Post image updated...!'
    }
except Exception as e:
    print(e)
    resp = {
        'resp': 'Error: Post image update failed...!'
    }
return Response(resp)

Code doesn't throw errors but does not work as expected. In the database it stores the value as image_name.jpeg;

Expected value to be stored: post_images/1640341471608.jpeg

CodePudding user response:

you have to create a method that will rename the files after upload and before saving there are many tutorials demonstrating this.

CodePudding user response:

in views.py

@api_view(['POST'])

def save_edited_post_image(request):
image = request.data.get('image')
print('image == ')
print(request.data.get('image'))
post_id = request.data.get('post_id')
print('post id = ' str(post_id))
im = request.FILES['image']
print(im)
try:
    post = GroupPostsModel.objects.get(id=post_id)
    try:
        os.remove(post.image.path)
        print('Old post image deleted...! path = ' str(post.image.path))
    except Exception as e:
        print('No image for delete ' str(e))

    post.image = request.FILES['image'] #Worked..
    
    post.save()
    resp = {
        'resp' : 'Post image updated...!'
    }
except Exception as e:
    print(e)
    resp = {
        'resp': 'Error: Post image update failed...!'
    }
return Response(resp)
  •  Tags:  
  • Related