Home > Enterprise >  How do i get Django to store already uploaded cover image to a user without getting it deleted
How do i get Django to store already uploaded cover image to a user without getting it deleted

Time:02-12

How do i get Django to store already uploaded cover image to a user without getting it deleted when a new image is uploaded, but simply replace it? I'm having a challenge trying to figure out how to maintain old cover images while adding new once to a user. what happens is that when i upload a new cover image it simply deletes the previous one from the database. Here is my cover image models:

class AccountCover(models.Model):
    account = models.ForeignKey(Account,on_delete=models.CASCADE)
    cover_image = models.ImageField(max_length=255,upload_to=get_cover_cover_image_filepath,default=get_default_cover_image,)

My view.py

 cover = AccountCover.objects.filter(account=account.id).first()
    if request.user:
        forms = CoverImageForm(request.POST, request.FILES,instance=cover,
                        initial = {'cover_image':cover.cover_image})
      
    if request.method == 'POST':
        f = CoverImageForm(request.POST, request.FILES,instance=cover)
        if f.is_valid():
             data = forms.save()
             data.account = cover.account
             data.save()
             return redirect('account:edit', account.id)
            
    else:
        f = CoverImageForm()
    context['f'] = f 

CodePudding user response:

You can keep old instances of AccountCover by forcing the form to save a new one each time. Simply remove the instance argument in the form, and remember save the form with commit=false before to set the account foreign key.

forms = CoverImageForm(request.POST, request.FILES, initial={'cover_image': cover.cover_image})

# ...
data = forms.save(commit=False)
data.account = cover.account
data.save()

I guess you need to preserve the old database record, not just the image file. An image file without any relation to the user's registry has no utility.

  • Related