Zealot91
Zealot91

Reputation: 155

UpdateView FileField not deleting previous files Django python

I have:

class UserUpdateView(UpdateView):
fields = ("file_one", "file_two")
model = User

And it works... but not always, I put in another file, and the paths change, but when I go a process the file in another def, it keeps the previous file values, I came to know because I checked my media folder to see if it was there and It was in the corresponding folder but also all the other files I had tested and read. I had to manually delete them and only the it took my new file.

How do I delete the previus file? or do I need to do:

def Inputfiles(request):
form = UploadFilesForm(request.POST, request.FILES, instance=request.user)
if request.method == "POST":

    if form.is_valid():
        form.save()
        return redirect('index')
    else:
        form = UploadFilesForm()

    return render(request, 'registration/File_Upload.html', {'form': form})
else:
    return render(request, 'registration/File_Upload.html', {'form': form})

The only thing I cant think of doing is add a

request.user.file_one.delete() from [documentation delete()][1] 

but I don't know where to put suck line if it would even work.

models.py

class User(AbstractUser):
email = models.EmailField(unique=True)
file_one = models.FileField(upload_to='csvfiles', validators=[FileExtensionValidator(allowed_extensions=['csv'])])
file_two = models.FileField(upload_to='csvfiles', validators=[FileExtensionValidator(allowed_extensions=['csv'])])

Upvotes: 0

Views: 850

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

You can override model's save() like this to remove old files during update:

class User(AbstractUser):
    ...
    def save(self, *args, **kwargs):
        if self.pk:
            this_record = User.objects.get(pk=self.pk)
            if this_record.file_one != self.file_one
                this_record.file_one.delete(save=False)
        super(User, self).save(*args, **kwargs)

Upvotes: 2

Related Questions