1. Create a form for updating data
class StockUpdateForm(forms.ModelForm):
class Meta:
model = Stock
fields = ['category', 'item_name', 'quantity']
2. Import the form created in step 1 then create a view to handle and process update request.
def update_items(request, pk):
queryset = Stock.objects.get(id=pk)
form = StockUpdateForm(instance=queryset)
if request.method == 'POST':
form = StockUpdateForm(request.POST, instance=queryset)
if form.is_valid():
form.save()
return redirect('/list_items')
context = {
'form':form
}
return render(request, 'add_items.html', context)
3. Create a URL/PATH to pass the ID of the object to be updated
path('update_items/<str:pk>/', views.update_items, name="update_items"),
4. In the items_list page, and an anchor linked to the update URL/PATH
<td><a href="{% url 'update_items' instance.id %}">{{instance.item_name}}</a></td>
The best project ever
Thanks for that comment.
Hi Arbadjie, I’ve been following your coding and it has been helpful. Thanks. But I’ve still got a need for your help, on the update_items, i have done up to the 3rd step but it is not giving me the desired result. When i enter “http://127.0.0.1:8000/update_items/2/” it gives me this error
“The view stockmgnt.views.update_items didn’t return an HttpResponse object. It returned None instead.”
Please is there something else i need to do other than the steps highlighted here??
In views.py, check that you have a return statement for this view: update_items
HIe Arbadjie,
whenevr i put update link it display all fields blank it does not show details hence i again need add category,item_name etc…
help
Check if you assigned the instance field in the form
form = YourForm(request.POST or None, instance=instance)
Traceback (most recent call last):
File “D:\django\venv\lib\site-packages\django\core\handlers\exception.py”, line 47, in inner
response = get_response(request)
File “D:\django\venv\lib\site-packages\django\core\handlers\base.py”, line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File “D:\django\venv\src\stockmgmt\views.py”, line 46, in update_items
queryset = Stock.objects.get(id=pk)
File “D:\django\venv\lib\site-packages\django\db\models\manager.py”, line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File “D:\django\venv\lib\site-packages\django\db\models\query.py”, line 435, in get
raise self.model.DoesNotExist(
hi
I have this probleme and i dont khnow why ??
probleme : BaseForm.__init__() got an unexpected keyword argument ‘instance’
in my views.py