0

我正在使用 Django 开发拍卖网站。我正在尝试显示 Last_bid 字段的数据,该字段使用外键连接到投标表。我尝试了很多方法,但都没有成功。models.py 文件是:

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models.base import Model
from django.db.models.deletion import CASCADE
from django.db.models.fields import CharField
from django.utils import timezone


class User(AbstractUser):
    pass


class Category(models.Model):
    category = models.CharField(max_length=64)

    def __str__(self):
        return f'{self.category}'


class AuctionListing(models.Model):
    item_name = models.CharField(max_length=100)
    item_image = models.ImageField(upload_to="products", null=True, blank=True)
    detail = models.TextField()
    price = models.IntegerField()
    last_bid = models.ForeignKey('Bid', on_delete=models.CASCADE, blank=True, null=True, related_name='lst')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='publisher_listing', null=True, blank=True)
    watchers = models.ManyToManyField(User, blank=True, related_name='watched_list')
    pub_date = models.DateTimeField(auto_now=True, null=True)
    deadline = models.DateTimeField(null=True)
    list_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, related_name='sortion')
    closed = models.BooleanField(default=False)
    
    def __str__(self):
        return f'{self.item_name} - {self.price}'


class Bid(models.Model):
    bid = models.IntegerField()
    user = models.ForeignKey(User, on_delete=CASCADE)
    auction = models.ForeignKey(AuctionListing, on_delete=CASCADE)
    bid_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f'{self.bid}-{self.auction}'


class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=CASCADE)
    com = models.TextField()
    pub_date = models.DateField()
    com_item = models.ForeignKey(AuctionListing, on_delete=models.CASCADE, related_name='get_comment')

    def __str__(self):
        return f'{self.user} - {self.pub_date}'
    

视图.py:

from django.contrib.auth import authenticate, login, logout
# from django.contrib.auth.decorators import login_required
from django.db import IntegrityError, reset_queries
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.urls import reverse
from django.forms import ModelForm

from .models import *


def index(request):
    active_list = AuctionListing.objects.all().order_by('id').reverse()
    return render(request, "auctions/index.html", {'active_list': active_list })


def login_view(request):
    if request.method == "POST":

        # Attempt to sign user in
        username = request.POST["username"]
        password = request.POST["password"]
        user = authenticate(request, username=username, password=password)

        # Check if authentication successful
        if user is not None:
            login(request, user)
            return HttpResponseRedirect(reverse("index"))
        else:
            return render(request, "auctions/login.html", {
                "message": "Invalid username and/or password."
            })
    else:
        return render(request, "auctions/login.html")


def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse("index"))


def register(request):
    if request.method == "POST":
        username = request.POST["username"]
        email = request.POST["email"]

        # Ensure password matches confirmation
        password = request.POST["password"]
        confirmation = request.POST["confirmation"]
        if password != confirmation:
            return render(request, "auctions/register.html", {
                "message": "Passwords must match."
            })

        # Attempt to create new user
        try:
            user = User.objects.create_user(username, email, password)
            user.save()
        except IntegrityError:
            return render(request, "auctions/register.html", {
                "message": "Username already taken."
            })
        login(request, user)
        return HttpResponseRedirect(reverse("index"))
    else:
        return render(request, "auctions/register.html")



class CreateForm(ModelForm):
    class Meta:
        model = AuctionListing
        fields = ['item_name', 'item_image', 'detail', 'price', 'deadline', 'list_category']
        

def create_listing(request):
    user = request.user
    if user.id is None:
        return redirect('login')

    
    if request.method == 'GET':
        context = {
            'form': CreateForm()
        }
        return render(request, 'auctions/create_listing.html', context)

    else:
        if request.method == 'POST': 
            form = CreateForm(request.POST or None, request.FILES or None)
            if form.is_valid():
                item_name = form.cleaned_data['item_name']
                item_image = form.cleaned_data['item_image']
                detail = form.cleaned_data['detail']
                price = form.cleaned_data['price']
                deadline = form.cleaned_data['deadline']
                list_category = form.cleaned_data['list_category'] 

                listing_created = AuctionListing.objects.create(
                    item_name = item_name,
                    item_image = item_image,
                    detail = detail,
                    price = price,
                    deadline = deadline,
                    list_category = list_category,
                    user = request.user,
                )
                listing_created.save()
                return redirect('index')


def listing(request, pk):
    user = request.user

    list = AuctionListing.objects.get(id=pk)
    if request.method == 'POST':
        bid = request.POST.get('placebid')
        user = request.user
        form = Bid(bid=bid, user=user, auction=list)       
        form.save()

    return render(request, 'auctions/listing.html', {'list': list})



index.html 是:

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

{% block body %}
    <h2>Active Listings</h2>
    
    {% for each in active_list %}
        <div class="back">
            <div class="imag">
                <img src="{{ each.item_image.url }}" alt="">
            </div>
            <div class="detail">
                <a href="{% url 'listing' each.id  %}"><h1>{{ each.item_name }}</h1></a>
                <h6>Published by: <span>{{ each.user }}</span></h6>
                {% if each.last_bid %}
                    <p>Current Bid: <span>{{ each.last_bid.bid }} </span></p>
                {% else %}
                    <p>Current Bid: <span>{{ each.price }} </span></p>
                {% endif %}
                <p>Published date: <span>{{ each.pub_date }}</span></p>
                <p>DeadLine: <span>{{ each.deadline }}</span></p>

                <div class="bid-detail">
                    <p>Initial Price: {{ each.price }}</p>
                    <p>Watchers: 10</p>
                </div>
            </div>
        </div>
    {% endfor %}
{% endblock %}

我想在 index.html 中显示 last_bid 但我做不到。请帮我解决这个问题。我会感谢你的。

4

0 回答 0