How to update the ImageField in Django Model using django form?

Issue

I am trying to update an ImageField in Django model using a Django form, but the pic is not getting updated.

Here is my Django model:

class Shop(models.Model):
    name = models.CharField(max_length=100)
    .
    .
    .
    cover_image = models.ImageField(
        blank=True, null=True, upload_to="covers/%Y/%M/%D"
    )

and here is my Django form to edit Shop:

class PostForm(forms.ModelForm):

    class Meta:
        model = Shop
        fields = ('name', ..., 'cover_image')

and here is the HTML of the form:

  <form method="POST" class="post-form" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form|crispy }}

      <div class="row ">
        <div class="col-5 col-md-6">
          <button type="submit" class="btn form_btn">Save</button>
        </div>
      </div>
  </form>

and here is my view to handle editing:

def shop_edit(request, pk):
    shop = get_object_or_404(Shop, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST or None, request.FILES or None,instance=Shop())
        if form.is_valid():
            shop = form.save(commit=False)
            shop.cover_image=form.cleaned_data['cover_image']
            shop.save()
            return redirect('shop_detail', pk=shop.pk)
    else:
        form = PostForm(instance=shop)
    return render(request, 'shops/shop_edit.html', {'form': form})

When I add an image while adding a new shop the image is uploaded. But when I try to update that image via edit shop it doesn’t get updated.

Solution

If you want to handle the django image field by yourself then remove the'cover_image' from the fields in your django form or simply remove the commit=False in your view while saving the form and let the django form handle.
Change your view like this

def shop_edit(request, pk):
    shop = get_object_or_404(Shop, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST or None, request.FILES or None,instance=shop)
        if form.is_valid():
            shop = form.save()
            return redirect('shop_detail', pk=shop.pk)
    else:
        form = PostForm(instance=shop)
    return render(request, 'shops/shop_edit.html', {'form': form})

Answered By – arjun

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published