Django UpdateView / ImageField issue: not returning new uploaded image
Asked Answered
B

3

12

model:

class Logo(models.Model):
    media = models.ImageField(upload_to='uploads')

    def __unicode__(self):
      return self.media.url

view:

class LogoEdit(UpdateView):
  model = Logo
  template_name = 'polls/logo-edit.html'
  success_url = '/polls/logos/'

  def form_valid(self, form):
    pdb.set_trace()

template:

  <form id="my_form" action="" method="post">{% csrf_token %}
      {{ form.as_p }}
      <input type="submit" value="Save Changes" />
  </form>

selecting new image:

form

debug view:

existing image:

(Pdb) self.object
<Logo: media/uploads/DSCN0844.JPG>

form with new selected image (DSC_0021.JPG):

(Pdb) test = form.save()
(Pdb) test
<Logo: media/uploads/DSCN0844.JPG>

As you can see the original image remains in form!

Boylston answered 6/3, 2015 at 16:5 Comment(1)
Can you please explicitly ask a question? E.g. I don't see anywhere in your template that you are trying to render the uploaded image.Subnormal
F
21

If you are using UpdateView, you only need to add enctype="multipart/form-data" attribute to the form tag in your template. The rest will be handled by UpdateView class.

Finis answered 24/1, 2016 at 5:4 Comment(2)
<form method="POST" enctype="multipart/form-data"> - it worked, thank youHerman
Had the same issue, adding <enctype="multipart/form-data"> to the form solved it!Chafin
U
6

You need to save the form providing request.FILES:

if request.method == 'POST':
    form = MyForm(request.POST, request.FILES)
    if form.is_valid():
        form.save()

And in your HTML form (since you have an <input type="file"> in the form):

<form method="POST" enctype="multipart/form-data">
Unprepared answered 6/3, 2015 at 16:19 Comment(1)
<form method="POST" enctype="multipart/form-data"> - That was it, thank youHerman
G
3

just add to your template

 <form method="POST" enctype="multipart/form-data">
Grapevine answered 24/12, 2020 at 18:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.