[英]AttributeError at /addtowatchlist/5: 'QuerySet' object has no attribute 'listings'
在我的應用程序中,我允許任何給定用戶將拍賣列表添加到他們的監視列表中,但無論我嘗試了什么,它似乎都不起作用,而且我一直在標題中收到錯誤消息。 我只是想訪問發出請求的用戶並將列表添加到他們的監視列表並將他們重定向到主頁。
視圖.py
from .models import *
def add_to_watchlist(request, listing_id):
listing = Listing.objects.get(id=listing_id)
# Retrieving the user watchlist (where it always fails)
watchlist = PersonalWatchList.objects.filter(user=request.user)
# Fails here too
if (watchlist.listings.all() == None) or (listing not in watchlist.listings.all()):
watchlist.listings.add(listing)
watchlist.save()
else:
messages.error(request, "Listing is already in your Watchlist.")
return redirect(reverse('index'))
messages.success(request, "Listing added to your Watchlist.")
return redirect(reverse('index'))
模型.py
class PersonalWatchList(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
listings = models.ManyToManyField(Listing, blank=True)
def __str__(self):
return f"Watchlist for {self.user}"
網址.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("create", views.createListing, name="create"),
path("view/<str:listing_title>", views.view, name="view"),
path("addtowatchlist/<int:listing_id>", views.add_to_watchlist, name="add_to_watchlist")
]
用於將列表添加到監視列表的模板部分
<div class="listing-actions">
<a href= {% url 'view' listing.title %} class="btn btn-primary view-button">View</a>
<!--TODO: Make watchlist-->
<a href={% url 'add_to_watchlist' listing.id %} class="btn btn-primary add-to-watchlist-button">Watchlist</a>
</div>
我嘗試過使用 try 和 except 改變我的邏輯,但它仍然會導致非常相似的錯誤。 在我的 urls.py 中,我嘗試更改路徑名稱以避免它們重疊,因為“view”和“add_*to_*watchlist”之前很相似,但該更改仍然無效。 之前,在
監視列表 = PersonalWatchList.objects.filter(user=request.user)
我改為使用 get() ,但它也不起作用。 任何提示將非常感謝!
編輯:當我通過 django 管理員將列表添加到給定用戶監視列表時,效果很好,我真的不明白如何,但是通過服務器本身它失敗了
要檢索單個用戶的監視列表,請使用 get 而不是過濾器:
watchlist = PersonalWatchList.objects.get(user=request.user)
使用 filter() 方法返回一個 QuerySet(多個對象),而不是您想要的單個唯一對象。
另一個問題在您的 model 定義中。 要使用默認用戶 class 作為外鍵,您需要使用
轉動這個:
user = models.ForeignKey(User, on_delete=models.CASCADE)
進入這個:
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
試試這個並評論你的結果。
我基本上不得不改變我的邏輯,因為我了解到引發此錯誤的原因是因為用戶在 PersonalWatchList Model 中尚不存在。這是更新的解決方法。
views.py 已更新
def add_to_watchlist(request, listing_id):
user = request.user
# Getting the listing that was clicked
listing = Listing.objects.get(id=listing_id)
# Retrieving the user watchlist (if it exists)
try:
watchlist_exists = PersonalWatchList.objects.get(user=request.user)
except:
watchlist_exists = None
# If there isn't one for this user, make one
if watchlist_exists == None:
PersonalWatchList.objects.create(user=user)
# Access that watchlist
watchlist = PersonalWatchList.objects.get(user=user)
# Comparing the listings already present in their watchlist to the one that was hit
if (listing not in watchlist.listings.all()):
watchlist.listings.add(listing)
watchlist.save()
else:
messages.error(request, "Listing is already in your Watchlist.")
return redirect(reverse('index'))
messages.success(request, f"'{listing}' added to your Watchlist.")
return redirect(reverse('index'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.