Я получил IntegrityError с системой Bid в моем проекте Django

Ошибка Django: IntegrityError at /Post/18/bid Сбой ограничения NOT NULL: auctions_bid.bidWon Метод запроса: POST URL запроса: http://127.0.0.1:8000/Post/18/bid Версия Django: 3.2.8 Тип исключения: IntegrityError Значение исключения:
Не удалось выполнить ограничение NOT NULL: auctions_bid.bidWon

Я пытаюсь применить эту Спецификацию:

  • Если пользователь авторизован и является тем, кто создал объявление, у него должна быть возможность "закрыть" аукцион с этой страницы, что делает победителя аукциона, сделавшего наивысшую ставку, победителем аукциона и делает объявление более не активным.
  • Если пользователь вошел на страницу закрытого объявления, и он выиграл аукцион, на странице должно быть написано об этом.

но когда я запускаю сервер, я получаю эту ошибку

Пожалуйста, взгляните на мой код:

url.py

urlpatterns = [
# bids Close Bid
path('Post/<int:id>', views.viewList, name='viewList'),
path("Post/<int:id>/bid", views.take_bid, name="take_bid"),
path('Post/<int:id>/close', views.closeListing, name="closeListing"),
]

model.py

# DONE

class Post(models.Model):

# data fields
title = models.CharField(max_length=64)
textarea = models.TextField()

# bid!!!!!!!!!!!
startBid = models.FloatField(default=0)
currentBid = models.FloatField(blank=True, null=True)

imageurl = models.CharField(max_length=255, null=True, blank=True)
category = models.ForeignKey(
    Category, on_delete=models.CASCADE, default="No Category Yet!", null=True,  blank=True)

creator = models.ForeignKey(
    User, on_delete=models.PROTECT, related_name="all_creators_listings")

watchers = models.ManyToManyField(
    User, blank=True, related_name='favorite')
date = models.DateTimeField(auto_now_add=True)

# for activated the Category
activate = models.BooleanField(default=True)

buyer = models.ForeignKey(
    User, null=True, on_delete=models.PROTECT)

def __str__(self):
    return f"{self.title} | {self.textarea} |  {self.date.strftime('%B %d %Y')}"


class Bid(models.Model):
         auction = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="item_id")
         user = models.ForeignKey(User, on_delete=models.CASCADE)
         bid = models.FloatField()

views.py

def viewList(request, id):
# check for the watchlist
listing = Post.objects.get(id=id)
if listing.watchers.filter(id=request.user.id).exists():
    is_watched = True
else:
    is_watched = False
context = {
    'listing': listing,
    'comment_form': CommentForm(),
    'comments': listing.get_comments.all(),
    'is_watched': is_watched,
    'Bidform': BidForm()
}
return render(request, 'auctions/item.html', context)

def is_valid(bid, listing):
if bid >= listing.startBid and (listing.currentBid is None or bid > listing.currentBid):
    return True
else:
    return False


@login_required
def take_bid(request, id):
listing = Post.objects.get(id=id)
bid = float(request.POST['bid'])
if is_valid(bid, listing):
    listing.currentBid = bid
    form = BidForm(request.POST, request.FILES)
    newBid = form.save(commit=False)
    newBid.auction = listing
    newBid.user = request.user
    newBid.save()
    listing.save()
    return HttpResponseRedirect(reverse("viewList", args=[id]))
else:
    return render(request, "auctions/item.html", {
        "listing": listing,
        "Bidform": BidForm(),
        "error_min_value": True
    })

def closeListing(request, id):
        listing = Post.objects.get(id=id)
        if request.user == listing.creator:
                listing.activate = False
                listing.buyer = Bid.objects.filter(auction=listing).last().user
                listing.save()
                return HttpResponseRedirect(reverse('viewList', args=[id]))
        else:
                listing.watchers.add(request.user)
                return HttpResponseRedirect(reverse("watchlist_list"))

item.html

 <!-- Close Listing -->
<div class="close-btn">
{% if  listing.creator == user %}
    <a class="btn btn-outline-info" href="{% url 'closeListing' listing.id %}" role="button">Close</a>
{% endif %}
</div>

                    <div class="newbid">
                {% if user.is_authenticated %}
                <li class="list-group-item">
                    {% if listing.currentBid is None %}
                        {% if listing.creator != user  %}
                            <p class="text-muted">Start the first Bid!</p>
                        {% else %}
                        {% endif %}
                    {% elif listing.buyer is not None %}
                        {% if listing.creator == user %}
                        {% if listing.buyer == user %}
                        <p class="text-muted">You've won this auction!</p>
                        {% endif %}
                        {% endif %}
                    {% else %}
                            Current price: {{ listing.currentBid }}
                    {% endif %}

                    {% if error_min_value %}
                        {% if listing.currentBid %}
                            <div class="alert alert-warning" role="alert">Your bid must be bigger than {{ listing.currentBid }}</div>
                        {% else %}
                            <div class="alert alert-warning" role="alert">Your bid must be equal or bigger than {{ listing.currentBid}}</div>
                        {% endif %}
                    {% endif %} 

                    {% if listing.activate and listing.creator != user %}
                    <div class="form-group">
                        <form action="{% url 'take_bid' listing.id %}" method="post">
                            <br>
                            <small class="text-muted">Edit Your Crunnt Bid:</small>
                            <br>
                            {% csrf_token %}
                            {{ Bidform }}        
                            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                <input type="submit" value="Edit" class="btn btn-primary btn-sm m-1"/>
                            </div>
                        </form>                    
                    </div>         
                    {% endif %}
                {% else %}
                <div class="alert alert-light" role="alert">
                    <a href="{% url 'login' %}">log in</a> to start the Bid!
                </div>
                {% endif %}
                </div>
Вернуться на верх