1👍
✅
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, theget_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 aModelForm
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 useProductInfoForm
instead of
.update_product_info
Source:stackexchange.com