问题描述
我正在尝试显示一个列表页面。尽管显示良好,但django仍会出现以下错误:
提高self.model.DoesNotExist( auctions.models.Listing.DoesNotExist:列表匹配查询不存在。
索引视图通过迭代显示所有列表,列表视图通过接收变量“ form.title”显示特定的列表视图。
我的代码如下:
views.py:
def listing_view(request,title):
# if get a listing page
categories = Category.objects.all()
# Get all the forms submitted
forms = Listing.objects.all()
# get the highest bid for a listing
highest_price = Bid.objects.filter(title=title).order_by("-bid_price").first()
# Get the listing with the title
listing = Listing.objects.get(title=title)
if highest_price is not None:
listing.current_price = highest_price.bid_price
# else set starting price as the current price
else:
listing.current_price = listing.starting_price
listing.save()
index.html:
<!-- image of a listing -->
<div class="col-4">
<a href="{% url 'listing_view' form.title %}">
{% if form.image %}
<img src="{{ form.image.url }}" alt="" width="267px" />
{% elif form.image_url %}
<img src="{{ form.image_url }}" alt="" width="267px" />
{% endif %}
</a>
</div>
listing.html:
<!-- image in the left of the container -->
<div class="col-4">
{% if listing.image %}
<img src="{{ listing.image.url }}" alt="" width="267px" />
{% elif listing.image_url %}
<img src="{{ listing.image_url }}" alt="" width="267px" />
{% endif %}
</div>
这里的html文件是为了澄清列表页面显示中需要变量“ listing”,因为它说不存在,所以我尝试使用try和except而不是statement,但是它给了我另一个错误下方:
UnboundLocalError:分配前已引用本地变量“列表”
我了解我将其设置为局部变量,因此返回渲染无法到达它。
但是如何获得没有错误的列表对象?
任何帮助表示赞赏!
谢谢!
解决方法
可能存在与更多事情相关的错误,请确保您已通过以下方式进行了MIGRATION和MIGRATED列表模型的迁移
python manage.py makemigrations
python manage.py migrate
如果正确完成,请确保在视图的返回值中listing_view传递类似这样的上下文
return render(request,'yourdir/index.html)