Django SimpleLazyObject

时间:2013-07-12 20:11:07

标签: python django django-templates django-views

当我尝试提交时,我收到一个TypeError:

  

int()参数必须是字符串或数字,而不是'SimpleLazyObject'

我的views.py:

def bookmark_save_page(request):
    if request.method == 'POST':
        form = BookmarkSaveForm(request.POST)
        if form.is_valid():
            # Create or get link.
            link, dummy = Link.objects.get_or_create(
                url=form.cleaned_data['url']
                )
            # Create or get bookmarks.
            bookmark, created = Bookmark.objects.get_or_create(
                user = request.user,
                link = link
                )
            # Update bookmark title.
            bookmark.title = form.cleaned_data['title']
            # If the bookmark is being updated, clear old tag list.
            if not created:
                bookmark.tag_set.clear()
            # Create new tag list.
            tag_names = form.cleaned_data['tags'].split()
            for tag_name in tag_names:
                tag, dummy = Tag.objects.get_or_create(name=tag_name)
                bookmark.tag_set.add(tag)
            # Save bookmark to database.
            bookmark.save()
            return HttpResponseRedirect(
                '/user/%s/' %request.user.username
                )
    else:
        form = BookmarkSaveForm()

    variables = RequestContext(request, {'form': form})
    return render_to_response('bookmark_save.html',variables)

请指导我。 谢谢。

2 个答案:

答案 0 :(得分:12)

request.user,默认情况下为SimpleLazyObject类型。要解决它,

bookmark, created = Bookmark.objects.get_or_create(
            user = request.user,
            link = link
            )

应该是

bookmark, created = Bookmark.objects.get_or_create(
            user = request.user.id,
            link = link
            )

如果仍无法解决此问题,请确保您已登录。

答案 1 :(得分:1)

还有另一种选择,可能这个解决方案可以帮助您解决问题。

from django.contrib import auth

bookmark, created = Bookmark.objects.get_or_create(
        user = auth.get_user(request),
        link = link
        )