Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django UpdateView / ImageField issue: not returning new uploaded image

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!

like image 613
Gunnar Thielebein Avatar asked Mar 06 '15 16:03

Gunnar Thielebein


3 Answers

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.

like image 183
Code_Data Avatar answered Sep 29 '22 14:09

Code_Data


just add to your template

 <form method="POST" enctype="multipart/form-data">
like image 31
Samir Aljuaid Avatar answered Sep 29 '22 15:09

Samir Aljuaid


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">
like image 24
nima Avatar answered Sep 29 '22 15:09

nima