Issue
I'm making a simple form in Django without using the in-built Django forms. To process the form I'm just using HTML/Django template and Python in the views.py file.
I don't understand why print(bid > highest_bid)
is returning True when:
Highest bid = 2000.6
bid = 3
listing_detail.html
<form method="POST" action="{% url 'listing-detail' object.id %}">
{% csrf_token %}
<input type="hidden" name="highest_bid" value="{{ highest_bid }}">
<input type="number" step=".01" min="" placeholder="0.00" name="bid">
<button type="submit">Place bid</button>
</form>
views.py
# place bid
highest_bid = request.POST.get("highest_bid", "") #2000.6
print(f'Highest = {highest_bid}')
bid = request.POST.get("bid", "") #3
print(f'bid = {bid}')
print(bid > highest_bid) # returns True
if 'bid' in request.POST and bid > highest_bid:
#bid = float(request.POST['bid'])
new_bid = Bids(bid_value=bid, bidder=self.request.user, item=item)
new_bid.save()
return redirect(reverse("listing-detail", args=listing_id))
This means that the bid is being saved to the database. Even though I am trying to only save the highest bid with the line
if 'bid' in request.POST and bid > highest_bid:
Solution
The problem is that you are comparing string not number.to avoid this you should cast your variable something like this.
print(int(bid) > int(highest_bid)) or print(float(bid) > float(highest_bid))
try to change this
if 'bid' in request.POST and bid > highest_bid:
to
if 'bid' in request.POST and float(bid) > float(highest_bid):
Answered By - amadou sow
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.