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!

  • 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. – Charlie Mar 06 '15 at 16:13

3 Answers3

19

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.

Code_Data
  • 321
  • 2
  • 3
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">
nima
  • 6,566
  • 4
  • 45
  • 57
2

just add to your template

 <form method="POST" enctype="multipart/form-data">
Sami
  • 95
  • 2
  • 6