AttributeError: 'tuple' object has no attribute '_committed'

后端 未结 1 789
情书的邮戳
情书的邮戳 2021-01-17 06:31

models.py

class Image(models.Model):
    title = models.CharField(max_length=255)
    image = models.ImageField(upload_to=\'attack_images\', blank=True, null=         


        
相关标签:
1条回答
  • 2021-01-17 06:38

    When working with ImageField or FileField you actually operate on instance of FieldFile

    And error in this case is assigning wrong type to ImageField - it expects FieldFile or at least File type.


    Brief answer what can be used instead of self.image = .... in your code:

    from django.core.files import File
    
    ...
    
    with open(result[0], "rb") as downloaded_file:
        self.image.save(os.path.basename(self.source_url), File(downloaded_file), save=False)
    ...
    

    Check this StackOverflow answer on saving files. I added a small change - save=False - while saving image - at this step we only save downloaded file = copying it from temporary path, where it was downloaded by urllib to desired target path in MEDIA, but not saving model instance.

    self.image.save(name, file) - file is read and saved in MEDIA at upload_to path with name name and model instance is saved aftewards (default save=True).

    self.image.save(name, file, save=False) - the same, but model instance is not saved after the file has been altered, which is probably desired as you save model instance super().save() later.


    What steps are happening in your code:

    • downloading file with urllib (to temp path)
    • saving it / copying to correct media / upload_to path and setting ImageField to its value
    • setting other model instance fields
    • saving model
    0 讨论(0)
提交回复
热议问题