Reputation: 75
Am using Django to create a system that records available stock of a shop, and records the sales made. I have a 'Sell Item' button on every available item, so that the seller uses the button to record that a sale was made. So am requesting the pk(through the url) of the item on which the button was clicked(to know which item is being sold), and I also have a form where the seller will input the quantity being sold, so that I get how many items are being sold(Am trying to get this using the GET method). But am getting errors that quantity is None since am unable to get the quantity.
This is my template:
<td>
<form action="{% url 'stock:sell' pk=item.pk%}" method="GET">
<input type="number" id="quantity" value="1" size="5">
{% csrf_token %}
<button type="submit" name="submit">Sell</button>
</form>
</td>
This is my url:
path('sell/<pk>/', sell, name='sell'),
And this is my views:
def sell(request, pk):
if request.method == 'GET':
quantity_sold = request.GET.get('quantity')
item = Item.objects.get(id=pk)
if quantity_sold > int(item.quantity):
messages.danger(request, "Not enough stock to sell that quantity!")
else:
item.quantity -= quantity
item.save()
return HttpResponseRedirect(reverse('stock:show_stock'))
Am getting the quantity to make sure that only available quantity can be sold, and then to update to the database(to remove items that have been sold).
Am getting an error saying that quantity_sold is NoneType. How should I solve this or which is an easier way?
Upvotes: 0
Views: 765
Reputation: 49341
Since you are posting data you should be checking request.POST to retrieve the submitted data. It should be:
if request.method == 'POST':
quantity_sold = request.POST.get('quantity') # or request.POST['quantity']
When you get the form-data request.POST['quantity']
, this will be an object and its key values will be the "name" of the input fields. However you did not set any name for the input
<input type="number" name="quantity" id="quantity" value="1" size="5" required>
Upvotes: 1
Reputation: 119
Try this form:
<form action="{% url 'stock:sell' pk=item.pk%}" method="GET">
<input type="number" name="quantity" id="quantity" value="1" size="5" required>
{% csrf_token %}
<button type="submit" name="submit">Sell</button>
</form>
I hope this will work. If not comment.
Upvotes: 0