【发布时间】:2021-01-01 14:46:44
【问题描述】:
为这篇长文道歉,我正在尝试实现一个简单的按钮,可以在关注列表中添加或删除项目。
虽然我最初设法适当地实现了“addwatchlist”功能,但我修改了我的代码几个小时,但我有点无法再次理解它。
这是我按下 “添加到关注列表” 按钮时收到的错误:
TypeError at /addwatchlist/10
Field 'id' expected a number but got <Listing: "Gloss + Repair Spray">.
Request Method: GET
Request URL: http://127.0.0.1:8000/addwatchlist/10
Django Version: 3.1.1
Exception Type: TypeError
Exception Value:
Field 'id' expected a number but got <Listing: "Gloss + Repair Spray">.
追溯:
watchlist.save()
▼ Local vars
Variable Value
id 10
request <WSGIRequest: GET '/addwatchlist/10'>
watchlist Error in formatting: TypeError: Field 'id' expected a number but got <Listing: "Gloss + Repair Spray">.
这是我按下 “从监视列表中删除” 按钮时收到的错误,请注意,这与我最初收到的错误完全相同,这反过来又迫使我尝试调整方式“添加到关注列表”功能:
AssertionError at /removewatchlist/1
Watchlist object can't be deleted because its id attribute is set to None.
Request Method: GET
Request URL: http://127.0.0.1:8000/removewatchlist/1
Django Version: 3.1.1
Exception Type: AssertionError
Exception Value:
Watchlist object can't be deleted because its id attribute is set to None.
追溯:
watchlist.delete()
▼ Local vars
Variable Value
id 1
request <WSGIRequest: GET '/removewatchlist/1'>
watchlist <Watchlist: 1 Watchlist ID# None : admin watchlisted : "Iphone 11 Pro">
Models.py:
class Listing(models.Model):
owner = models.CharField(max_length=64)
title = models.CharField(max_length=64)
description = models.TextField(max_length=1024)
startingBid = models.IntegerField()
link = models.URLField(blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category_id")
time = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(null=False, default='True')
def __str__(self):
return f'"{self.title}"'
class Watchlist(models.Model):
user = models.CharField(max_length=64)
watchlist_listingid = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="watchlist_listingid", null=True)
def __str__(self):
return f'{self.watchlist_listingid_id} Watchlist ID# {self.id} : {self.user} watchlisted : {self.watchlist_listingid}'
Views.py:
@login_required
def watchlist(request):
if request.user.username:
return render(request, "auctions/watchlist.html", {
"items" : Watchlist.objects.filter(user=request.user.username),
"watchlist_listingid" : Watchlist.objects.values_list('watchlist_listingid', flat=True).filter(user=request.user.username),
"watchlist_count" : len(Watchlist.objects.filter(user=request.user.username))
})
def addwatchlist(request, id):
if request.user.username:
watchlist = Watchlist(user=request.user.username,watchlist_listingid_id=Listing.objects.filter(id=id).first())
watchlist.save()
return redirect('listing', id=id)
else:
return render('auctions/watchlist.html', {})
def removewatchlist(request, id):
if request.user.username:
# all_entries = Watchlist.objects.values_list('watchlist_listingid', flat=True).filter(user='admin')
# for i in all_entries:
# if i == id:
# removeMe = i
# else:
# removeMe = 'TEST ERROR'
watchlist = Watchlist(user=request.user.username,watchlist_listingid_id=id)
watchlist.delete()
return redirect('listing', id=id)
Urls.py:
path("listing/<int:id>", views.listing, name="listing"),
path("watchlist", views.watchlist, name="watchlist"),
path("addwatchlist/<int:id>", views.addwatchlist, name="addwatchlist"),
path("removewatchlist/<int:id>", views.removewatchlist, name="removewatchlist")
添加/删除按钮托管在 listing.html 上:
{% if user.is_authenticated %}
<p>
{% if watchlisted %}
<a href="{% url 'removewatchlist' item.id %}"><button class="btn btn-danger">Remove from watchlist</button></a>
{% else %}
<a href="{% url 'addwatchlist' item.id %}"><button class="btn btn-success">Add to watchlist</button></a>
{% endif %}
</p>
{% endif %}
问题:
- 我使用 Watchlist.watchlist_listingid 作为 上市的外键?我看过很多其他帖子 人们往往根本不使用外键,尽管我相信 可能没有优化。
- 我最终可能会使用表单来封装这些按钮,但我 我的listing.html 页面中已经有一个表单(添加cmets)。 尽管我没有处理表单中的数据可能会更容易 设法找出如何在 一个 HTML 页面。您认为最佳实践是什么?表格或直接 链接召唤功能?
- 对于“添加到关注列表”,为什么我获得
def __str__(self):return f'"{self.title}"'而不是简单地在我的 关注列表? - 最后,对于“从监视列表中删除”,当我知道在我的示例中,为什么我会收到
"id attribute is set to None"“Iphone 11 Pro”的 Listing.id 是 1,从技术上讲, Watchlist.id (在我的模型中根本没有显示)是 11 基于 Django 管理页面。甚至硬编码 11 以强制删除它 Watchlist 表仍然返回此“无”错误。
期待您的回复!
【问题讨论】:
标签: python django django-models foreign-keys