Как получить самую высокую ставку на аукционе на сайте торгов Django
Итак, у меня есть приложение Django auctions, которое имеет 3 модели: Пользователи, Объявления, Ставки. Когда пользователь пытается сделать ставку на какое-то объявление, я хочу проверить, больше ли поле new_bid в модели Bid, чем поле start current_bid в модели Listing, и если new_bid <= 0, то должно возвращаться сообщение.
Это то, что я сделал до сих пор, но когда я нажимаю на кнопку 'Place bid', он не выполняет это (он не показывает никакого сообщения для любого из вышеуказанных сценариев и мой счетчик не увеличивается), что означает, что форма не отправляется.
Почему это не работает?
VIEWS.PY
def listing_detail(request, listing_id):
try:
detail = get_object_or_404(Auction, pk=listing_id)
except Auction.DoesNotExist:
messages.add_message(request, messages.ERROR, "This is not available")
return HttpResponseRedirect(reverse("index"))
bid_count = Bids.objects.filter(auction=listing_id).count()
context = {'detail': detail, 'bid_count': bid_count, 'bidForm': BidForm()}
return render(request, 'auctions/details.html', context)
@login_required
def make_bid(request, listing_id):
if request.method == 'POST':
form = BidForm(request.POST)
if form.is_valid:
each_listing = Auction.objects.get(pk=listing_id)
highest_bid = Bids.objects.filter(pk=listing_id).order_by('-new_bid').first()
new_bid = form.cleaned_data.get['new_bid']
if new_bid <= 0:
return render(request, 'auctions/details.html',
{"message": "Input an amount greater than 0"})
# messages.add_message(request, messages.SUCCESS, "Input an amount greater than 0")
elif new_bid <= highest_bid.new_bid:
messages.add_message(request, messages.ERROR, "Amount is low, please increase the bid")
else:
highest_bid = Bids(each_listing=each_listing, user=request.user, new_bid=new_bid)
highest_bid.save()
each_listing.current_bid = new_bid
each_listing.save()
return HttpResponseRedirect(reverse("index"))
messages.add_message(request, messages.SUCCESS, "Your bid is currently the highest")
else:
form = BidForm()
return render(request, 'auctions/details.html', {'bidForm': form})
else:
form = BidForm()
return render(request, 'auctions/details.html', {'bidForm': form})
MODELS.PY
class User(AbstractUser):
pass
class Auction(models.Model):
title = models.CharField(max_length=25)
description = models.TextField()
current_bid = models.IntegerField(null=False, blank=False)
image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Meta:
ordering = ['-created_at']
class Bids(models.Model):
auction = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name='bidding')
user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='bidding')
new_bid = models.DecimalField(max_digits=8, decimal_places=2)
# new_bid = MoneyField(max_digits=10, decimal_places=2, null=False, blank=False, default_currency='USD')
done_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['auction', '-new_bid']
FORMS.PY
class AuctionForm(forms.ModelForm):
class Meta:
model = Auction
fields = ['title', 'description', 'current_bid', 'image_url', 'category']
class BidForm(forms.ModelForm):
class Meta:
model = Bids
fields = ['new_bid']
labels = {
'new_bid': ('Choose your maximum bid'),
}
DETAILS.HTML
<div class="row container">
<div class="col-sm-7 pr-5">
{% if detail.image_url %}
<img src='{{ detail.image_url }}' alt="{{ detail.title }}" style="width:100%">
{% else %}
<img src="https://demofree.sirv.com/nope-not-here.jpg">
{% endif %}
</div>
<div class="col-sm-5">
<div style="width: 30rem;">
<div>
<h5>{{ detail.title }}</h5>
<hr>
<p>{{ detail.description }}</p>
<hr>
<p>${{ detail.current_bid }}</p>
<p>{{ bid_count }}</p>
<hr>
<form action="{% url 'listing_detail' detail.id %}" method="post">
{% csrf_token %}
{{ bidForm }}
<input type="submit" class="btn btn-primary btn-block mt-3" value="Place bid">
</form>
<button class="btn-block btn-outline-primary mt-3">Add to watchlist</button>
</div>
</div>
</div>