1

I am using Django 1.6. I have a model for uploading image files that looks like this.

class Image(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)
    url = models.ImageField(upload_to=get_image_path,
                             null=True,
                             blank=True,
                             height_field = 'height',
                             width_field = 'width',
                             verbose_name='Image')
    height = models.IntegerField(blank=True)
    width = models.IntegerField(blank=True)
    size = models.IntegerField(blank=True)
    format = models.CharField(max_length=50)
    caption = models.CharField(max_length=255)


    def clean(self):
        self.size = self.url.size

    class Meta:
        db_table = 'image'

As you can see, I am storing the size of the image when the clean() method is called. This works for what I want to do, but is this best practise? Is there a better way to automatically save the image's file size when saving?

The second part of my question is how can I get the content type as well?

Thanks, Mark

2 Answers 2

1

Model.clean() should be used for validation - do not use it to update/save the data, but rather use it to correct any invalid data (or throw an exception/error message).

You may want to consider not even storing the size of the image in the database, given that you can access it from the ImageField - it eliminates the possibility of the data becoming inconsistent as it changes over time.

I believe this question/answer should address your second question.

Sign up to request clarification or add additional context in comments.

Comments

0

For the first question
Check out the Python Imaging Library PIL on this thread.

from PIL import Image
im=Image.open(filepath)
im.size # (width,height) tuple

For the second question
HttpRequest.META, more specifically HttpRequest.META.get('CONTENT_TYPE') from this thread

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.