拍卖时显示最高出价

2024-10-01 05:05:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想显示有人在拍卖清单上的最新出价,但它会显示所有出价。我还想做一个功能,不允许出价低于实际最高出价

models.py

class Bid(models.Model):
    auction =  models.ForeignKey(Auction, on_delete=models.CASCADE, related_name="bids")
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    new_bid = models.IntegerField()

views.py(我在拍卖页面上已经有了新的投标表格)

@login_required(login_url="login")
def auction(request, id=id): 
    auction = Auction.objects.get(pk=id)
    new_bid = Bid.objects.last()
    
    if request.method == "POST":
        form = PlaceNewBid(request.POST or None, request.FILES or None)
        if form.is_valid():
            user = request.user
            new_bid = form.cleaned_data["new_bid"]
            comment = Bid(auction=auction, user=user, new_bid=new_bid)
            comment.save()     
    else:
        form = Lcreate()   
    return render(request, "auctions/listing.html", {
        "form": PlaceNewBid,
        "comments": auction.comments.all(),
        "auction": auction,
        "bids": auction.bids.all(),
        "new_bid": new_bid
        
    })

forms.py

class PlaceNewBid(forms.ModelForm):
    class Meta:
        model = Bid
        fields = ('new_bid',) 

html

<form method="POST" enctype="multipart/form-data">
                {%csrf_token%}
                <button type="submit" class="btn btn-primary">Place a New Bid</button>
                {{form.as_p}}
            </form>
            {%for bid in bids%}
            <h3>${{ bid.new_bid}}</h3>
            {%empty%}
            No offers yet.
            {%endfor%}
            {{auction.description}}
       ```  
I hope everything is understandable, thanks

Tags: pyformidnewmodelsrequestloginpost
1条回答
网友
1楼 · 发布于 2024-10-01 05:05:08

要限制投标金额,您只需使用表格的验证方法:

class PlaceNewBid(forms.ModelForm):
    class Meta:
        model = Bid
        fields = ('new_bid',) 
    
    def clean_new_bid(self):
        bid = self.cleaned_data.get('new_bid')
        # get the top bid
        top_bid = Bid.objects.order_by("-new_bid").first()
         if not top_bid:
             return bid

        # compare the bid with the top bid
        if bid <= top_bid.new_bid:
            raise ValidationError("Your bid is too small!")

为了显示最后一次出价:

首先,您需要获取最后一次出价并将其传递给模板(您正在传递所有出价):

@login_required(login_url="login")
def auction(request, id=id): 
    ... 
    return render(request, "auctions/listing.html", {
        ....
        "last_bid": auction.bids.order_by("-new_bid").first(),
        ...
    
    })

然后显示最后一个(无需使用for循环):

<h3>${{ last_bid.new_bid}}</h3>

相关问题 更多 >