django CS50 Web项目2:如何保存起拍价

jgwigjjp  于 2023-04-22  发布在  Go
关注(0)|答案(1)|浏览(96)

我正在为CS50 Web编程课程(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 %}

我很感激你的支持,
哈维尔

a5g8bdjr

a5g8bdjr1#

您可以尝试更改Listing模型中的startingBid字段,以允许该字段为空值,然后当给出出价时,您可以检查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()

相关问题