when you are using some already existing Model data or updating the database models data through the POST method, Sometimes you will face the above issue and the server will be crashing, also the data will be not updated right?
well, here is a small solution!
read the below code and you will understand it better.
I have created one small model for products on my site, now I am going to create an HTML form will we will be using for updating my models through the POST request or POST method.
here is the code.
Views.py functions for updating the database data.
def update(request, pk):
product = Product.objects.get(id=pk)
if request.method == 'POST':
product.name = request.POST.get('name')
product.price = request.POST.get('price')
product.desc = request.POST.get('desc')
try:
if request.FILES['upload']:
product.image = request.FILES['upload']
except:
pass
product.save()
return redirect('products')
context={
'product':product
}
return render(request, 'ecom/update.html', context) ```
I used the try and except functions here, because Django will give you an error when are over riding the data over other data fields, especially the ImageField give this error, so you can use the try and accept for bypassing the form if someone doesn't change the image. the server will be no crashing.