CS50 Web Project 2:如何保存起拍价

问题描述 投票:0回答:1

我正在为 CS50 网络编程课程(Django 中类似 eBay 的电子商务拍卖网站)进行项目 2,我想保存拍卖的起始出价,以便与以后的拍卖进行比较。

请看下面我的代码:

models.py

from django.contrib.auth.models import AbstractUser
from django.db import models

class User(AbstractUser):
    pass

class Category(models.Model):
    categoryName = models.CharField(max_length=20)

    def __str__(self):
        return self.categoryName
    
class Listing(models.Model):
    title = models.CharField(max_length=30)             
    description = models.CharField(max_length=100)                            
    imageUrl = models.CharField(max_length=500)         
    isActive = models.BooleanField(default=True)        
    price = models.IntegerField(default=0)              
    startingBid = models.IntegerField(default=0)        
    owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="user") 
    category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True, related_name="category") 
    watchlist = models.ManyToManyField(User, blank=True, null=True, related_name="listingWatchlist")

class Bid(models.Model):
    bid = models.IntegerField(default=0) 
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="userBid")    
    listing = models.ForeignKey(Listing, on_delete=models.CASCADE, blank=True, null=True, related_name="bidListing")           

class Comments(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="userComment")
    listing = models.ForeignKey(Listing, on_delete=models.CASCADE, blank=True, null=True, related_name="listingComment")
    comment = models.CharField(max_length=200)       

    def __str__(self):
        return f"{self.author} comment on {self.listing}"

添加出价的函数(进入views.py)

def addNewBid(request, id):

    currentUser = request.user
    listingData = Listing.objects.get(pk=id)

    isListWatchList = request.user in listingData.watchlist.all()

    allComments = Comments.objects.filter(listing=listingData)

    newBid = request.POST['newBid']

    isOwner = request.user.username == listingData.owner.username

    # The bid must be at least as large as the starting bid, and must be greater than any other bids that have been placed (if any). 
    # If the bid doesn’t meet those criteria, the user should be presented with an error.
    #
    if int(newBid) >= listingData.price.bid:
        updateBid = Bid(user = currentUser, bid = int(newBid))
        updateBid.save()
        listingData.price = updateBid
        listingData.save()

        return render(request, "auctions/listing.html", {
            "listing": listingData,
            "message": "Bid succesful: Current price was updated!",
            "update": True,
            "isListingWatchList": isListWatchList,
            "allComments": allComments,
            "isOwner": isOwner,
        })
    
    else:
        return render(request, "auctions/listing.html", {
            "listing": listingData,
            "message": "Bid failed!",
            "updated": False,
            "isListingWatchList": isListWatchList,
            "allComments": allComments,
            "isOwner": isOwner,
        })

listing.html

{% extends "auctions/layout.html" %}

{% block body %}

     {% if message %}
        {% if updated %}
             <div class="alert alert-success" role="alert">
                {{ message }}
            </div>
        {% else %}
             <div class="alert alert-warning" role="alert">
                {{ message }}
            </div>
        {% endif %}
    {% endif %}

    {% if not listing.isActive and user == listing.price.user %}
        <div class="alert alert-success" role="alert">
            Wow! You won the auction !
        </div>
    {% endif %}

    <h2>{{ listing.title }}</h2>
    <br>
    <p>{{ listing.description }}</p>
    <h5>Current price: ${{ listing.price.bid }}</h5>
    <p>Owner: {{ listing.owner }}</p>
    
    {% if user.is_authenticated %}
        <form action="{% url 'addNewBid' id=listing.id %}" method="POST">
            {% csrf_token %}
            <div class="form-group">
                <label for="comment">New Bid:</label>
                <input type="number" min="0" name="newBid" placeholder="">
                <button type="submit" class="btn btn-primary">Add</button>
            </div>            
        </form>

        {% if isOwner and listing.isActive %}
            <form action="{% url 'closeAuction' id=listing.id %}" method="POST">
                {% csrf_token %}
                <div class="col-md-12 text-center">
                    <button type="submit" class="btn btn-primary">Close Auction</button>
                </div>
            </form>
        {% endif %}
    {% endif %}

    <img src="{{ listing.imageUrl }}" alt="{{ listing.title }}" height="400px">
    <h2>Comments</h2>    
    <ul class="list-group">
        {% for i in allComments %}
            <li class="list-group-item">{{ i.comment }}
                <br>
                <p>Author: {{ i.author }}</p>
            </li>
        {% endfor %}
    </ul>
    <br>

    {% if user.is_authenticated %}
        <form action="{% url 'addNewComment' id=listing.id %}" method="POST">
            {% csrf_token %}
            <div class="form-group">
                <label for="comment">New Comment:</label>
                <input type="text" name="newComment" placeholder="">
                <button type="submit" class="btn btn-primary">Add</button>
            </div>            
        </form>
    {% endif %}

    {% if user.is_authenticated %}
        {% if isListingWatchList %}        
            <form action="{% url 'removeWatchList' id=listing.id %}" method="POST">
                {% csrf_token %}
                <div class="col-md-12 text-center">
                    <button type="submit" class="btn btn-primary">Remove from Watchlist</button>
                </div>             
            </form>
        {% else %}                
            <form action="{% url 'addWatchList' id=listing.id %}" method="POST">
                {% csrf_token %}
                <div class="col-md-12 text-center">
                    <button type="submit" class="btn btn-primary">Add to Watchlist</button>
                </div>               
            </form>
        {% endif %}
    {% endif %}

{% endblock %}

感谢您的支持,

哈维尔

python django
1个回答
0
投票

您可以尝试更改

startingBid
模型中的
Listing
字段以允许该字段的空值,然后在给出出价时,您可以检查startingBid是否为
null
,在这种情况下出价将是 起拍价,否则不变。

此外,

if int(newBid) >= listingData.price.bid:
需要更改为
if int(newBid) >= listingData.price:
,因为
price
字段现在只是一个整数,而不是
Bid

所以对于您的

Listing
模型:

class Listing(models.Model):
    title = models.CharField(max_length=30)             
    description = models.CharField(max_length=100)                            
    imageUrl = models.CharField(max_length=500)         
    isActive = models.BooleanField(default=True)        
    price = models.IntegerField(default=0) 
    # Change startingBid from default=0 to blank=True, null=True             
    startingBid = models.IntegerField(blank=True, null=True)        
    owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="user") 
    category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True, related_name="category") 
    watchlist = models.ManyToManyField(User, blank=True, null=True, related_name="listingWatchlist")

在您看来:

if int(newBid) >= listingData.price:
    # If no starting bid has been set
    if not startingBid:
        # Set the starting bid
        startingBid = int(newBid)
    updateBid = Bid(user = currentUser, bid = int(newBid))
    updateBid.save()
    listingData.price = updateBid.bid
    listingData.save()
© www.soinside.com 2019 - 2024. All rights reserved.