int() argument must be a string or a number, not 'SimpleLazyObject'

前端 未结 5 744
南方客
南方客 2020-12-13 19:33

I got, following Error messages,

TypeError at /save/ int() argument must be a string or a number, not \'SimpleLazyObject\'

Whi

相关标签:
5条回答
  • 2020-12-13 19:45

    The likely cause is that you're setting user = request.user, where request.user is not a real User object, but a SimpleLazyObject instance. See django: Purpose of django.utils.functional.SimpleLazyObject? for more details, but using request.user.id should fix your issue.

    0 讨论(0)
  • 2020-12-13 19:46

    Thats strange, I had the same problem and the same solution. After trying a bunch of alternatives I went back to user = request.user and it worked

    0 讨论(0)
  • 2020-12-13 19:55

    Most likely the user who is loading the page is not authenticated. Therefor the error is thrown. If you want to save a request.user reference to the database, you obviously have to ensure that only authenticated users are able to call the function.

    In your case there are two possibilities - add the "@login_required" decorator to the function or check if the user is authenticated inside the code. Here are the snippets:

    With Decorator:

    from django.contrib.auth.decorators import login_required
    
    @login_required
    def bookmark_save_page(request):
        if request.method == 'POST':
            form = BookmarkSaveForm(request.POST)
            if form.is_valid():
                # Do something
    

    OR - checking inside the code if the user is authenticated:

    def bookmark_save_page(request):
        if request.method == 'POST' and request.user.is_authenticated():
            form = BookmarkSaveForm(request.POST)
            if form.is_valid():
                # Do something
    
    0 讨论(0)
  • 2020-12-13 19:56

    You have to login when running this piece of code on localhost. Otherwise the request.user will be a SimpleLazyObject, then the errors comes out.

    0 讨论(0)
  • 2020-12-13 20:00

    Here you trying to create a Bookmark object based on request.user , but request.user is a SimpleLazyObject , so we can get a more secure user object by :

    from django.contrib import auth
    
    current_user = auth.get_user(request)
    

    and further your query should be

    bookmark, created = Bookmark.objects.get_or_create(
                        user=current_user,
                        link=link
                        )
    
    0 讨论(0)
提交回复
热议问题