Ver Mensaje Individual
  #1 (permalink)  
Antiguo 29/10/2012, 01:15
PoLiZe
 
Fecha de Ingreso: marzo-2008
Ubicación: Santa Cruz, Argentina
Mensajes: 433
Antigüedad: 16 años, 2 meses
Puntos: 5
Al cambiar algun campo, actualizar ImageField

Buenas gente, estoy haciendo mis primeros experimentos con Python, tratando de pasar mi web en PHP a Python.

Actualmente en mi web tengo lo siguiente,

Cuando agrego una nueva noticia se sube con una imagen, y cuando yo actualizo el campo "urltag", la imagen se copia y se borra la anterior.

Ahora en python, estoy tratando de hacer eso, logré que se copie la imagen, también puedo hacer que se borre la imagen anterior, pero el valor del ImageField queda igual, no sé como cambiarlo.

Este es mi models.py
Código Python:
Ver original
  1. from django.db import models, settings
  2. from datetime import datetime
  3. from django.forms import ModelForm
  4. from PIL import Image
  5. import urllib2, urlparse
  6. from django.core.files.base import ContentFile
  7. import os
  8. import shutil
  9. from django.core.files import File
  10. def upload_to(self, filename):
  11.     return 'prensa/%s' % (self.urltag+".jpg")
  12.  
  13. def has_changed(instance, field):
  14.     if not instance.pk:
  15.         return False
  16.     old_value = instance.__class__._default_manager.\
  17.              filter(pk=instance.pk).values(field).get()[field]
  18.     return not getattr(instance, field) == old_value
  19.  
  20.  
  21. class Comunicado(models.Model):
  22.     titulo = models.CharField(max_length=50)
  23.     contenido = models.TextField()
  24.     tags = models.CharField(max_length=255)
  25.     fecha_creado = models.DateTimeField(null=True, blank=True)
  26.     urltag = models.CharField(max_length=255)
  27.     photo = models.ImageField(upload_to=upload_to)
  28.    
  29.    
  30.  
  31.  
  32.  
  33.     def save(self, size=(200, 200),*args, **kwargs):
  34.        
  35.  
  36.         if not self.id and not self.photo:
  37.             return
  38.        
  39.         super(Comunicado, self, *args, **kwargs).save()
  40.        
  41.         pw = self.photo.width
  42.         ph = self.photo.height
  43.         nw = size[0]
  44.         nh = size[1]
  45.        
  46.         # only do this if the image needs resizing
  47.         if (pw, ph) != (nw, nh):
  48.             filename = str(self.photo.path)
  49.             image = Image.open(filename)
  50.             tags = self.tags + ".jpg"
  51.             pr = float(pw) / float(ph)
  52.             nr = float(nw) / float(nh)
  53.            
  54.             if pr > nr:
  55.                 # photo aspect is wider than destination ratio
  56.                 tw = int(round(nh * pr))
  57.                 image = image.resize((tw, nh), Image.ANTIALIAS)
  58.                 l = int(round(( tw - nw ) / 2.0))
  59.                 image = image.crop((l, 0, l + nw, nh))
  60.             elif pr < nr:
  61.                 # photo aspect is taller than destination ratio
  62.                 th = int(round(nw / pr))
  63.                 image = image.resize((nw, th), Image.ANTIALIAS)
  64.                 t = int(round(( th - nh ) / 2.0))
  65.                 print((0, t, nw, t + nh))
  66.                 image = image.crop((0, t, nw, t + nh))
  67.             else:
  68.                 # photo aspect matches the destination ratio
  69.                 image = image.resize(size, Image.ANTIALIAS)
  70.                
  71.             image.save(tags)
  72.        
  73.         if self.id:
  74.              
  75.             old = Comunicado.objects.get(pk=self.id)
  76.         old_value =  old.urltag
  77.        
  78.         url_nueva = "/home/archivos/public_html/prensa/" + self.urltag + ".jpg"
  79.         shutil.copy (filename, url_nueva)
  80.         filename = url_nueva
  81.         image_url = "http://archivos.brotecolectivo.com/prensa/"+ self.urltag + ".jpg" # get this url from somewhere
  82.         image_data = urllib2.urlopen(image_url, timeout=50)
  83.         filename2 = urlparse.urlparse(image_data.geturl()).path.split('/')[-1]
  84.         self.photo= filename2
  85.         self.photo.save(
  86.             filename2,
  87.             ContentFile(image_data.read()),
  88.             save=False
  89.         )
  90.  
  91.     class Meta:
  92.         db_table = 'comunicados_prensa'
  93.  
  94.     def __unicode__(self):
  95.         return self.titulo

En la última parte, traté de guardar la imagen usando self.photo.save (photo es mi ImageField), pero no funciona.

¿como podría hacer esto?, osea, que el ImageField se actualice sin subir de nuevo la imagen, solamente usando la URL del fichero renombrado al cambiar el urltag.

Desde ya muchas gracias y disculpas si no expliqué bien el problema.