[Django]-Cannot upload an image in django using ImageField

13👍

from django documentation, i think this can help (in the past this helped me):

Firstly, in order to upload files, you’ll need to make sure that your
element correctly defines the enctype as “multipart/form-data”

<form enctype="multipart/form-data" method="post" action="/foo/">

5👍

In your view where you create an instance of the form with post data, ensure you have provided request.FILES

form = PersonForm(request.POST, request.FILES)
👤lenny

1👍

This is a bit late, but ‘upload_to’ is not a method. It’s an attribute that represents the relative path from your MEDIA_ROOT. If you want to save an image in the folder ‘photos’ with the filename self.id, you need to create a function at the top of your model class. For instance:

class Person(models.Model):
    def file_path(instance):
        return '/'.join(['photos', instance.id])
    image = models.ImageField(upload_to=file_path)

Then when you are actually saving your image you would call:

person = Person(firstName='hey', lasteName='joe')
person.image.save(ImageObject.name, ImageObject)

More on the image file objects here.

More on upload_to here.

Leave a comment