1👍
✅
Use the Stock
object as initial value, so not queryset.item_name
, but queryset
(although since it is not a queryset, it is better to rename this to stock
):
from django.shortcuts import get_object_or_404
def create_order(request, pk):
stock = get_object_or_404(Stock, id=pk)
if request.method == 'POST':
form = CreateOrderForm(request.POST, initial={'order_item': stock})
if form.is_valid():
form.save()
else:
form = CreateOrderForm(initial={'order_item': stock})
context = {
'form':form
}
return render(request, 'add_items.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.
Source:stackexchange.com