为什么当 bid = 3 且 highest_bid = 2000 时,print(bid > highest_bid) 返回 true?



我在Django中做一个简单的表单,不使用内置的Django表单。为了处理表单,我只使用HTML/Django模板和views.py文件中的Python。

我不明白为什么print(bid > highest_bid)返回True时:
最高出价= 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))

这意味着出价被保存到数据库中。即使我试图只保存出价最高的行

if 'bid' in request.POST and bid > highest_bid:

问题是您正在比较字符串而不是数字。为了避免这种情况,你应该像这样强制转换变量:

print(int(bid) > int(highest_bid)) or print(float(bid) > float(highest_bid))

尝试改变这个

if 'bid' in request.POST and bid > highest_bid:

if 'bid' in request.POST and float(bid) > float(highest_bid):

最新更新