What Is the Easiest Way to Update an Image Field with the Content of a File

What is the easiest way to update an image field with the content of a file

UPDATE YourTable
SET BlobColumn =
(SELECT BulkColumn FROM OPENROWSET(BULK N'C:\YourFile.png', SINGLE_BLOB) AS x)
WHERE ...

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

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)

How to get an image form field to update only if a new file has been chosen in django?

You forgot to add instance argument to the form constructor:

profile = Profil.objects.get(user=request.user)
form = ProfilForm(request.POST, request.FILES, instance=profile)

Update Django ImageField through .update() ORM

You can save your file separately to the media server with django's DefaultStorage class (see docs).

import os
import io
import requests
from django.conf import settings
from django.core.files.images import ImageFile
from django.core.files.storage import default_storage

response = requests.get(url)
full_name = url.split("/")[-1]
img_path = os.path.join(settings.MEDIA_ROOT, full_name)
image = ImageFile(io.BytesIO(response.content))
default_storage.save(img_path, image)

Update ImageField without forms in django

Update() method doesn’t run save().

Do something like this:

def update_product(request, product_id):
if request.method == "POST":
product = get_object_or_404(Product, id=product_id)
product.model_name = request.POST['model_name']
product.image = request.FILES['image']
product.save()
return redirect('listing')

Image src changes when i update the image but frontend displays the old image

Apparently your assets get cached, and there are multiple ways to solve that.

Not diving too much into caching strategies and cache control tags, just do

image.src = `${this.$fileHandler(image._id)}?_=${+new Date()}`

This will generate a unique (almost) URL for your image, invalidating every previous cached one.



Related Topics



Leave a reply



Submit