Forked from avoiney/FileField_manual_initialisation.py
          
        
    
          Created
          June 12, 2021 12:46 
        
      - 
      
- 
        Save simo97/ab0cbcbf3382e4f22ffde51a71363da9 to your computer and use it in GitHub Desktop. 
    Manually associate an existing file to a model FileField
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | # Assuming you have a Article Model like this | |
| # class Article(models.Model): | |
| # ... Some field | |
| # media = models.FileField(upload_to="path_to_inner_media_folder", blank=True) | |
| from django.core.files import ContentFile | |
| import os | |
| # Create an article with the associated model | |
| new_article = Article() | |
| original_file_path = 'path' | |
| new_file_path = 'new_path' | |
| fh = open(original_file_path, "r") | |
| if fh: | |
| # Get the content of the file | |
| file_content = ContentFile(fh.read()) | |
| # Set the media attribute of the article with or file, but under an other path/filename | |
| new_article.media.save(new_file_path, file_content) | |
| # Save the article | |
| new_article.save() | |
| # Close the file and delete it | |
| fh.close() | |
| if fh.closed: | |
| os.remove(unicode(fh.name)) | |
| del fh | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment