How to dynamically update Django Form min_value in a view?

Viewed 448

I am trying to create an auction site where a user can place a bid on an item. I'm storing a minimum bid within a model, and am retrieving that value when the view is loaded. I would like to use min_value to prevent a user from putting in a bid lower than min_bid.

I am not getting any sort of errors, it's just that the min_value is not working.

My form class:

class place_bid(forms.Form):
    bid_amount = forms.IntegerField(label="Bid Amount")
    def __init__(self, min_value, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['bid_amount'].min_value = 1

The view that loads the form (at this time I haven't written the part where I actually process the user submission, just trying to get the validation right first)

def listings(request, listing_id):
    listing = Listing.objects.get(id=listing_id)
    if request.method == "POST":
        min_bid = listing.min_bid
        return render(request, "auctions/listings.html", {
            "listing": listing,
            "bids": listing.bids.all(),
            "form": place_bid(min_value={"bid_amount":5})
        })
    if request.method == "GET":
        return render(request, "auctions/listings.html", {
            "listing": listing,
            "bids": listing.bids.all(),
            "form": place_bid(min_value={"bid_amount":5})
        })

The HTML:

    <form action="/listings/{{listing.id}}" method="post">
        {% csrf_token %}
        {{ form }}
        <button class="btn btn-primary" type="submit">Place Bid</button>
    </form>

I've tested removing all of the def __init__ stuff and changing bid_amount = forms.IntegerField(label="Bid Amount") to `bid_amount = forms.IntegerField(label="Bid Amount", min_value=5) and that works, but I need to be able to update it dynamically. I am assuming I'm doing something wrong with this syntax. Can someone please let me know what I need to change? Thanks so much!

Edit: Here is my bid model:

class Bid(models.Model):
    listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bids", blank=True)
    bid_amount = models.DecimalField(max_digits=10, decimal_places=2, null=True)
    bid_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bids", null=True)
    bid_time = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    def __str__(self):
        return f"The last bid on {self.listing} was {self.bid_amount}. Placed by {self.bid_by}"
0 Answers
Related