Django:在 ManyToManyField 中保存一个用户

Django: saving a User in ManyToManyField

我想做的是让经过身份验证的用户给一篇文章点赞。

models.py:

class NewsItem(models.Model):
  heading = models.CharField(max_length=550, blank = False)
  news_body = models.TextField(blank = True)
  ...
  likes = models.ManyToManyField(User, blank = True)

views.py:

def newsitem_slug(request, newsitem_id, slug):
  newsitem = get_object_or_404(NewsItem, pk=newsitem_id, active = 1)
  ...

  # Processing Likes:
  if request.method == 'POST' and request.POST.get('newsitem_like'):
    form = LikesForm(request.POST, instance=newsitem)
      if form.is_valid():
        user = User(id=request.user.id)
        if user not in newsitem.likes.all():
            newsitem.likes.add(user)
        else:
            newsitem.likes.remove(user)
  ...

forms.py:

class LikesForm(ModelForm):
    class Meta:
        model = NewsItem
        fields = ['likes',]

添加赞时出错:

Cannot add "<User: >": instance is on database "default", value is on database "None"

建议在使用 add 方法之前同时保存用户和文章,但在我的情况下似乎不起作用。

对此可以做些什么?

您正在创建一个 User 对象,如果您打算这样做,请在使用前保存它。如果您打算通过 id 获取 User 对象,请使用模型管理器 .get(pk=request.user.id) 获取它。