Elton Tan
Elton Tan

Reputation: 49

Check if a file exist in Django

I have created a newclaim.html and editclaims.html. newclaims.html allows me to upload a file while editclaims.html allows me to retrieve the file.

Currently, I am able to retrieve the uploaded file but I want to do an if-else. I want to do an if-else that will delete the old file if a new file is uploaded

This is my views.py

**# Submit a new Claim**
def newclaim(request):
      
      context = initialize_context(request)
      user = context['user']
      if request.method == 'POST':
          
          receipt = request.FILES['receipt_field']
        
          ins = SaveClaimForm(receipt=receipt)
          ins.save()
          print("The Data has been written")
    
      return render(request, 'Login/newclaim.html/', {'user':user})
    

   

 # Edit a claim
        def editclaims(request,id):
            context = initialize_context(request)
            user = context['user']
        
            # get original object     
            claims = SaveClaimForm.objects.get(id=id)
        
            if request.method == 'POST':
        
                # update original object
              
                claims.receipt = request.FILES.get('receipt')
        
                # save it with original `ID`
                claims.save()
              
            return render(request, "Login/editclaims.html", {'claims':claims, 'user':user})
      

Upvotes: 1

Views: 1110

Answers (1)

trigo
trigo

Reputation: 387

You can check if the old file exist in your file path and delete it. May refer to the code below and modify as per your need :

def editclaims(request,id):
        context = initialize_context(request)
        user = context['user']
    
        # get original object     
        claims = SaveClaimForm.objects.get(id=id)
    
        if request.method == 'POST':
            # get the old file name:
            old_file = claims.receipt

            # update original object
    
            claims.receipt = request.FILES.get('receipt')
    
            # save it with original `ID`
            claims.save()
            
            #Delete the old file from os if it exist
            #Do not forget to import os

            #FILE_PATH = path to your file directory
            if os.path.isfile(FILE_PATH+old_file):
                os.remove(FILE_PATH+old_file)

          
        return render(request, "Login/editclaims.html", {'claims':claims, 'user':user})

Upvotes: 3

Related Questions