Home > Back-end >  Why my product photo is not updating? But product title is updating
Why my product photo is not updating? But product title is updating

Time:08-18

I have an update form to update information. Here problem is, product_title is updating but product_image is not working. Where is the problem that's for why the photo is not updating?

views.py:

def update_product(request,id):
    product = Products.objects.get(pk=id)
    form = update_product_info(request.POST or None, instance=product)
    
    if request.method == 'POST' and form.is_valid():
        form.save()
        print(form.errors)
        messages.success(request,"Successfully product information updated.")
        return redirect("my_products")

    context = {
        'product':product,
        "form":form
    }
    
    return render(request, "update_product.html", context)

update form:

class update_product_info(forms.ModelForm):

    class Meta:
        model = Products
        fields = ('product_title','product_image')

        widgets = {
            'product_title':forms.TextInput(attrs={'class':'form-control', 'style':'font-size:13px;'}),
         
            'product_image':forms.FileInput(attrs={'class':'form-control', 'style':'font-size:13px;'})
        }

template:

<form action="" method="POST"  style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data">
    {% csrf_token %}
    {{form.as_p}}
                           
                           
     <div >
           <button type="submit"  value="Update" style="font-size: 13px;">Add</button>
    </div>

CodePudding user response:

You should pass both request.POST and request.FILES to the form:

from django.shortcuts import get_object_or_404


def update_product(request, id):
    product = get_object_or_404(Products, pk=id)
    if request.method == 'POST':
        form = update_product_info(request.POST, request.FILES, instance=product)
        if form.is_valid():
            form.save()
            messages.success(request, 'Successfully product information updated.')
            return redirect('my_products')
    else:
        form = update_product_info(instance=product)
    context = {'product': product, 'form': form}
    return render(request, 'update_product.html', context)

Note: It is often better to use get_object_or_404(…) [Django-doc], then to use .get(…) [Django-doc] directly. In case the object does not exists, for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using .get(…) will result in a HTTP 500 Server Error.


Note: normally a Django model is given a singular name, so Product instead of Products.


Note: Usually a Form or a ModelForm ends with a …Form suffix, to avoid collisions with the name of the model, and to make it clear that we are working with a form. Therefore it might be better to use ProductInfoForm instead of update_product_info.

  • Related