Cannot identify image file ImageFieldFile

495 views Asked by At

I'm using django with Python, in my models.py I declared a Tournament model with and attribute image, this is the save method:

import datetime
from django.db import models
from django.utils import timezone
from tinymce.models import HTMLField
from rules.models import Rule
from news.models import Tag, News
from courts.models import Court
from news.models import replace_spaces
from datetime import datetime
from sorl.thumbnail import ImageField, get_thumbnail
from PIL import Image
from django.core.files.storage import default_storage as storage
from django.conf import settings

class Tournament(models.Model):
    name = models.CharField(max_length=50, default='', verbose_name='Nombre')
    name_url = models.CharField(max_length=200, default='', editable=False)
    inscription_opening_date = models.DateField('fecha de apertura de inscripcion')
    inscription_closing_date = models.DateField('fecha de cierre de inscripcion')
    tournament_starting_date = models.DateField('fecha de inicio del torneo')
    tournament_ending_date = models.DateField('fecha de finalizacion del torneo')
    description = HTMLField(default='', verbose_name='Descripcion del Torneo', blank=True)
    image = ImageField(upload_to='tournamentpic', verbose_name='Imagen')
    situation = models.ForeignKey(TournamentSituation, default='', verbose_name='Estado del Torneo')
    tournament_format = models.ForeignKey(TournamentFormat, default='', verbose_name='Formato del Torneo')
    regulation = models.ForeignKey(Rule, default='', verbose_name='Reglamento')
    tournament_type = models.ForeignKey(TournamentType, default='', verbose_name='Tipo de Torneo')
    tournament_category = models.ForeignKey(TournamentCategory, default='', verbose_name='Categoria de Torneo')
    quota = models.IntegerField(default=0, verbose_name='Cupos')
    tag = models.ManyToManyField(Tag)
    price = models.DecimalField(default=0, max_digits=6, decimal_places=2, blank=True)
    zones = models.IntegerField(default=0, verbose_name='Zonas', blank=True)
    KNOCKOUT_OPENING_CHOICES = (
        ('64', 'Ronda de 128'),
        ('32', 'Ronda de 64'),
        ('16', 'Ronda de 32'),
        ('8', 'Octavos de Final'),
        ('4', 'Cuartos de Final'),
        ('2', 'Semifinal'),
    )
    knockout_opening_round = models.CharField(max_length=2, verbose_name='Instancia de Inicio de Llaves', choices=KNOCKOUT_OPENING_CHOICES, default='32', blank=True)
    singles = models.IntegerField(default=0, verbose_name='Numero de Singles', blank=True)
    doubles = models.IntegerField(default=0, verbose_name='Numero de Doubles', blank=True)
    photo_full_size = models.CharField(max_length=255, blank=True, editable=False)



def save(self):
    self.name_url = replace_spaces(self.name)
    sizes = {'full': {'height': 415, 'width': 620},}

    extension = self.image.name.rsplit('.', 1)[1]  # the file extension
    now = datetime.now()
    date = now.strftime("%H-%M-%S-%d-%m-%Y")
    self.image.name = date +'.png'
    filename = date

    super(Tournament, self).save()
    default_format = 'PNG'
    im = Image.open(self.image)

    if extension not in ['jpg', 'jpeg', 'gif', 'png']: sys.exit()

    new_size = im.resize((sizes['full']['width'], sizes['full']['height']), Image.ANTIALIAS)
    medname = "-" + str(sizes['full']['width']) + "x" + str(sizes['full']['height']) + ".png"
    thumb_path = UPLOAD_TO + filename + medname
    fh = storage.open(thumb_path, "w")
    new_size.save(fh,default_format)
    fh.close()
    self.photo_full_size = thumb_path

When I save a new tournament in my admin, I get the following error:

cannot identify image file <ImageFieldFile: 16-16-58-19-06-2015.png>

Im uploading my pictures and media files to S3. The strange thing is that in another model, with the exact same configuration it works perfectly! Here the other model:

from django.db import models
from tinymce.models import HTMLField
from datetime import datetime
from sorl.thumbnail import ImageField, get_thumbnail
from PIL import Image
from django.core.files.storage import default_storage as storage
from django.conf import settings

import sys

MEDIA_URL = getattr(settings, 'MEDIA_URL')

UPLOAD_TO = 'aboutpic/'

class Name(models.Model):
    name = models.CharField(max_length=20, default='', verbose_name='Nombre')
    lastname = models.CharField(max_length=20, default='', verbose_name='Apellido')

    def __str__(self):            
        return self.name + ' ' + self.lastname

class About(models.Model):
    image = ImageField(upload_to='aboutpic', verbose_name='Imagen de Portada')
    introduction = HTMLField(default='', verbose_name='Cuerpo de Noticia', blank=True)
    creation_date = models.DateField('fecha de publicacion', default=datetime.now(), editable=False)
    names = models.ManyToManyField(Name)
    photo_full_size = models.CharField(max_length=255, blank=True, editable=False)

    def save(self):
        sizes = {'full': {'height': 415, 'width': 620},}

        extension = self.image.name.rsplit('.', 1)[1]  # the file extension
        now = datetime.now()
        date = now.strftime("%H-%M-%S-%d-%m-%Y")
        self.image.name = date +'.png'
        filename = date

        super(About, self).save()
        print self.image
        default_format = 'PNG'
        im = Image.open(self.image)
        if extension not in ['jpg', 'jpeg', 'gif', 'png']: sys.exit()

        new_size = im.resize((sizes['full']['width'], sizes['full']['height']), Image.ANTIALIAS)
        medname = "-" + str(sizes['full']['width']) + "x" + str(sizes['full']['height']) + ".png"
        thumb_path = UPLOAD_TO + filename + medname
        fh = storage.open(thumb_path, "w")
        new_size.save(fh,default_format)
        fh.close()
        self.photo_full_size = thumb_path

        super(About, self).save()

    def get_full_size(self):
        return MEDIA_URL + self.photo_full_size
1

There are 1 answers

0
Gal Silberman On

And here is the comment as an actual answer:

In admin.py:

def response_change(self, request, obj): 
    obj.save()  
    return HttpResponseRedirect(
        reverse('admin:tournaments_tournament_change', args=(obj.id,))
    ) 

def response_add(self, request, obj, post_url_continue=None): 
    obj.save()  
    return HttpResponseRedirect(
        reverse('admin:tournaments_tournament_change', args=(obj.id,))
    )