1

I am trying to update an image field in django model from an html form. Update goes fine except for the image field. Originally I successfully uploaded this image within a django form which means the settings are fine.

Please, tell me what's wrong in my code.

That's my views.py file: '''

def update_product(request, product_id):
    if request.method=="POST"
        model_name=request.POST['model_name']
        image = request.FILES ['image']
        Product.objects.filter(id=product_id).update(model_name=model_name, image=image)
        return redirect ('listing)

''' That's my html file: '''

<form action={% url update_product product.id %} method ="POST enctype='multipart/form-data'>
{% csrf_token %}
<input type='text' name='model_name'>
<input type='file' name='image'>
<button type='submit'> Update </button>
</form>
Sergei
  • 93
  • 1
  • 6

1 Answers1

1

Update() method doesn’t run save().

Do something like this:

def update_product(request, product_id):
    if request.method == "POST":
        product = get_object_or_404(Product, id=product_id)
        product.model_name = request.POST['model_name']
        product.image = request.FILES['image']
        product.save()
        return redirect('listing')
Andy
  • 654
  • 7
  • 17
  • Hey, I am using `.save()` but still same happens when using `.update()`. The file name in the admin panel updates successfully but the image doesnt store in the `media` folder. Can you identify the ttpe of mistake that might have caused my problem?? – Meet Gondaliya Apr 10 '22 at 13:44