我一直在尝试基于 Django 在我的网站上实现购物车。
以下是我使用的模型:
class ShoppingCart(models.Model):
songs = models.ManyToManyField(Song)
albums = models.ManyToManyField(Album)
class Listener(User):
name = models.CharField(max_length=200, blank=True, null=True)
bio = models.TextField(blank=True, null=True)
cart = models.ForeignKey(ShoppingCart, blank=True, null=True)
这是views.py
我收到错误消息的地方None Type Object has no attribute songs at request.user.listener.cart.songs.add()
:
def add_to_cart(request):
if not request.user.is_authenticated() or not request.method == 'POST':
return HttpResponse(json.dumps({'success':False}), content_type='application/json')
typeobj = request.POST.get('type', None)
obj = request.POST.get('id', None)
if typeobj is None or obj is None:
return HttpResponse(json.dumps({'success':False}), content_type='application/json')
if typeobj == 'album':
try:
album = Album.objects.get(pk=obj)
except ObjectDoesNotExist:
return HttpResponse(json.dumps({'success':False}), content_type='application/json')
request.user.listener.cart.albums.add(Album.objects.get(pk=obj))
else:
try:
song = Song.objects.get(pk=obj)
except ObjectDoesNotExist:
return HttpResponse(json.dumps({'success':False}), content_type='application/json')
request.user.listener.cart.songs.add(Song.objects.get(pk=obj))
return HttpResponse(json.dumps({'success':True}), content_type='application/json')
我检查了外壳,当我尝试将歌曲添加到购物车时发生了同样的错误。它说 cart 是一个NoneType
对象,没有属性songs
。
提前致谢。