提问人:Schultzy11 提问时间:11/18/2023 最后编辑:Schultzy11 更新时间:11/19/2023 访问量:63
我正在努力使用 Django 模板语言在 for 循环中创建一个 if 条件。CS50w 项目2
I'm struggling to create a if condition within a for loop with Django template language. CS50w Project2
问:
在此处查看我的代码 https://gist.github.com/Schultzy11/d93bc34d13adc1263337604c44827147
我有一个带有“listings”变量的for循环,可以对其进行索引以创建我想要的值。
但是当我尝试使用 top_bids 变量创建一个 if 条件并使用 .listings.id 索引到其中时,它并没有给我预期的结果。
供参考
当我打印 top_bids 变量时,我得到 .{1: 700.0, 2: None}
我希望得到:第一篇文章显示最高出价:700 美元,第二篇显示起价 10000 美元
这是我目前得到的
html.py
{% extends "auctions/layout.html" %}
{% block body %}
<h2>Active Listings</h2>
<div class="container">
{% for listing in listings %}
<div class="card mb-3 mt-4">
<div class="row g-0 align-items-center">
<div class="col-md-4" style="max-width: 300px; max-height: 300px;">
<img src="{{listing.image_url}}" class="img-fluid rounded-start" alt="{{listing.title}}">
</div>
<div class="col-md-8 ">
<div class="card-body">
<h3 class="card-title">{{listing.title}}</h3>
<p class="card-text">{{listing.description}}</p>
{% if top_bids.listing.id == None %}
<p class="card-text">Start Price: ${{listing.start_bid}}</p>
{% else %}
<p class="card-text">Top Bid: ${{ top_bids.listing.id }}</p>
{% endif %}
<p class="card-text"><small class="text-body-secondary">Created: {{listing.date_created}}</small></p>
<div class="mt-4">
<a href=""><button class="btn btn-primary">View</button></a>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
models.py
from django.contrib.auth.models import AbstractUser
from datetime import datetime
from django.db import models
class User(AbstractUser):
pass
class Listings(models.Model):
title = models.CharField(max_length=50)
description = models.TextField()
start_bid = models.FloatField()
image_url = models.URLField(blank=True, null=True)
category = models.ForeignKey("Categories", on_delete=models.PROTECT)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.id}: {self.title} starting at {self.start_bid} in {self.category} on {self.date_created}"
class ListingsOwned(models.Model):
user = models.ForeignKey("User", on_delete=models.CASCADE)
listing = models.ForeignKey("Listings", on_delete=models.CASCADE)
class Bids(models.Model):
user = models.ForeignKey("User", on_delete=models.CASCADE)
listing = models.ForeignKey("Listings", on_delete=models.CASCADE)
amount = models.FloatField()
def __str__(self):
return f"{self.user} bid {self.amount} on {self.listing.title}"
class Comments(models.Model):
user = models.ForeignKey("User", on_delete=models.CASCADE)
listing = models.ForeignKey("Listings", on_delete=models.CASCADE)
comment = models.TextField()
class Categories(models.Model):
category = models.CharField(max_length=40)
def __str__(self):
return f"{self.category}"
views.py
from django import forms
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .models import User, Categories, Listings, Bids
class NewListing(forms.Form):
title = forms.CharField(max_length=50, label="Title", required=True)
description = forms.CharField(required=True, label="Description")
start_bid = forms.FloatField(required=True, label="Starting Bid")
image_url = forms.URLField(required=False, label="Image URL" )
category = forms.ModelChoiceField(queryset=Categories.objects.all())
def index(request):
# get all listing information
listings = Listings.objects.all()
# get list of ids
ids = Listings.objects.all().values('id')
# initiate top bids dict
top_bids={}
# loop to check for top bids else set None
for row in ids:
# check there are bids
listing_id = row['id']
try:
top_bid = Bids.objects.filter(listing = listing_id).order_by("-amount")[0]
top_bid = top_bid.amount
top_bids[listing_id] = top_bid
except IndexError:
top_bids[listing_id] = None
print(top_bids)
return render(request, "auctions/index.html", {
"listings": listings, "top_bids": top_bids
})
答: 暂无答案
评论
{% if top_bids.listing.id == None %}