添加用户实例时,django 对象中的书签得到了 simplelazyobject 为什么

Bookmarks in django object got simplelazyobject when adding user instance Why

浪费了很多时间研究和试图找出如何在 django 中实现书签。我试过 CBV 但我放弃了。我试过 fbv 但我一直收到这个错误:

TypeError at 'Bookmark' instance expected, got SimpleLazyObject: User: ****

这是我的看法:

@login_required
def company_bookmark(request, slug):
    user = request.user
    model = get_object_or_404(Company, slug=slug)
    if user.is_authenticated:
        if model.bookmark.filter(id=user.id).exists():
            model.bookmark.remove(request.user)
        else:
            model.bookmark.add(request.user)
            return HttpResponseRedirect(model.get_absolute_url())
    else:
        messages.warning(request, 'you must be authenticated first')

我把它包装在条件语句中,但仍然出现同样的错误,我在 html 中添加了条件,但无济于事

    {% if request.user.is_authenticated %}
    <a href="{% url 'company:bookmark' slug=company.slug %}"
       value="{{ company.slug }}" type="submit" class="btn_1 full-width outline wishlist">
      <i class="icon_heart"></i> Add to Favourite
    </a>
    {% endif %}

我什至试过添加 id 来查看这样的内容

model.bookmark.remove(request.user.id)

它带来另一个错误:

AttributeError at
'int' object has no attribute '_state'

这是模型

class Company(models.Model):
    name = models.CharField(max_length=120, help_text='Name of your company', )
    slug = models.SlugField(unique=True, blank=True, null=True)
    bookmark = GenericRelation(Bookmark,  related_query_name='company_bookmark')

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        slug = slugify(self.name)
        self.slug = slug
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('company:detail', kwargs={'slug': self.slug})


class Bookmark(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

和错误

Traceback:

File "C:\Users\postgres\desktop\job\env\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\postgres\desktop\job\env\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\postgres\desktop\job\env\lib\site-packages\django\core\handlers\base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\postgres\desktop\job\env\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  21.                 return view_func(request, *args, **kwargs)

File "C:\Users\postgres\desktop\biz\src\bookmarks\views.py" in company_bookmark
  18.             model.bookmark.add(request.user)

File "C:\Users\postgres\desktop\job\env\lib\site-packages\django\contrib\contenttypes\fields.py" in add
  598.                     check_and_update_obj(obj)

File "C:\Users\postgres\desktop\job\env\lib\site-packages\django\contrib\contenttypes\fields.py" in check_and_update_obj
  585.                         self.model._meta.object_name, obj

Exception Type: TypeError at /company/inceptor-kenya/bookmark
Exception Value: 'Bookmark' instance expected, got <SimpleLazyObject: <User: Gracelynn>>

如果能得到帮助,我将不胜感激。提前致谢。

出现错误是因为您需要向 model.bookmark 添加 Bookmark 实例而不是 User 实例(其中 modelCompany实例)。

您的代码:

if model.bookmark.filter(id=user.id).exists():
    model.bookmark.remove(request.user)
else:
    model.bookmark.add(request.user)

可以改成这样,例如:

# search bookmarks of this 'Company' with this 'user'
bookmark = model.bookmark.filter(user=user).first()

if bookmark is not None:
    bookmark.delete()
else:
    bookmark = Bookmark()
    bookmark.user = request.user
    bookmark.content_object = model
    bookmark.save()