Почему фото товара не обновляется? Но название товара обновляется

У меня есть форма для обновления информации. Проблема в том, что product_title обновляется, но product_image не работает. Где проблема, почему фото не обновляется?

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)

форма обновления:

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;'})
        }

Шаблон:

<form action="" method="POST" class="needs-validation" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data">
    {% csrf_token %}
    {{form.as_p}}
                           
                           
     <div class="d-flex align-items-center">
           <button type="submit" class="btn btn-outline-dark ms-auto" value="Update" style="font-size: 13px;">Add</button>
    </div>

Вы должны передать обе request.POST и request.FILES в форму:

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.


Примечание: обычно модели Django дается сингулярное имя, поэтому Product вместо Products.


Примечание: Обычно Form или ModelForm заканчивается суффиксом …Form, чтобы избежать коллизии с именем модели, и чтобы было ясно, что мы работаем с формой. Поэтому, возможно, лучше использовать ProductInfoForm вместо update_product_info.

Вернуться на верх