[Fixed]-How to rename django image as id.jpg

2👍

You pass a function to upload_to. There you can set the filename and path of the image (https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to).
The function could look like this

def get_image_name(instance, filename):
    fn = 'mealsOne/static/meal_photos/%s.jpg' % instance.id
    return fn

And in you model pass this function

meal_image=models.FileField(upload_to=get_image_name);

UPDATE:

If the object is not yet created, there is no id set. Then you can overwrite the save method of the model and do there the renaming.

def save(self):
    super(Model, self).save(*args, **kwargs)
    # now the id is set
    # rename your image with os.rename
    ....

You can also do this using djangos post_save signal (https://docs.djangoproject.com/en/1.9/ref/signals/#post-save)

-1👍

A few notes:

  • don’t use ‘+’ to join urls, use urlparse.urljoin
  • for filesystem paths use os.path.join
  • why would use use “mv” and “self.save” in the unicode function which should be used for “rendering” the object?

Leave a comment