Search code examples
ajaxdjangopreviewdjango-modelsfilefield

Preview ImageField after "Choose File" button was selected


So I have a really basic form with an ImageField implemented

# form
class MyForm(forms.Form):       
    my_image = forms.ImageField(required=False)

# Model
class MyModel(models.Model):
    my_image = models.ImageField(upload_to="images", null=True, blank=True)

# view

my_model = MyModel.objects.create(
    my_image=cd['my_image'] )

It's working fine, now how can I preview the image right after the user press the button "choose file"? Is there any way to accomplish this with Django or shall I use Ajax?

thank you


Solution

  • This is best done on the client-side using JavaScript. All modern browsers now can do this using HTML5 file API. There is no need to round-trip the file from the server.

    Previous StackOverflow answer

    Related Mozilla documentation.