I need to update image for specific user Django

Question:

I need to update image for specific user Django . Now if I updating the image for specific user , image updates for all users . Is there any solutions ? Here is my code :

models.py

class UserWithImage(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)  
    image=models.FileField(upload_to='photos/%Y/%m/%d/',null=True,blank=True)
    def __str__(self):
        return self.user.username

views.py

if 'imagechange' in request.POST and request.FILES['image']:
    image = request.FILES['image']
    fs = FileSystemStorage()
    image_fs = fs.save(image.name, image)
    image_new = UserWithImage.objects.update(image=image_fs)

html page

    <form  id='myform' enctype="multipart/form-data" method="POST">
        {% csrf_token %}               
        <input type="file" class="settings__background__file" name="image" enctype="multipart/form-data"  id="backgroundimage" placeholder="Upload image">
    <button id="submit-image" name="imagechange" type="submit"> Upload Image </button>
     </form>
Asked By: Valera

||

Answers:

Yes you have to filter your queryset. You are currently updating all objects.

image_new = UserWithImage.objects.filter(user=request.user).update(image=image_fs)

or if you do not want to update the user which does the request you call it like

user = User.objects.get(id=1)
image_new = UserWithImage.objects.filter(user=user).update(image=image_fs)
Answered By: ChrisRob

You first need to select the user and then update the image. But after this, remember to remove the old image, it would still be stored in your media folder, even if it was replaced.

Here is how i would do it

if 'imagechange' in request.POST and request.FILES['image']:
    image = request.FILES['image']
    fs = FileSystemStorage()
    image_fs = fs.save(image.name, image)
    user_with_image = UserWithImage.objects.get(user=request.user)
    # get the old image path
    old_image_path = user_with_image.image.path
    #replace the image and save
    user_with_image.image = image_fs
    user_with_image.save()

    # delete the old image
    if os.path.exists(old_image_path):
        os.remove(old_image_path)
Answered By: MOHAMED HABI
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.