<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f49286ec100>>

I am encountering an error Field ‘id’ expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object

I started experiencing this challenge when I implemented monitor django application if user has not used it for 30 minutes and prompt them that the app will logout automatically

After the first log out, this problem started. I can no longer logon to my application again.

See the codes I implemented below

Setting.py

# Session Time Out
SESSION_COOKIE_AGE = 1800 # 30 minutes in seconds
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True

JavaScript

<!-- SweetAlert2 CSS --> 
   <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
<!-- SweetAlert2 JS -->
   <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script type="text/javascript">
      //<!-- Scritpt to Monitor Session time out.-->>
      (function () {
        let inactivityTimer;
        let warningTimer;
        const warningTime = 25 * 60 * 1000; // 25 minutes
        const logoutTime = 30 * 60 * 1000; // 30 minutes
    
        function resetTimers() {
            clearTimeout(warningTimer);
            clearTimeout(inactivityTimer);
    
            warningTimer = setTimeout(() => {
                Swal.fire({
                    title: "Inactivity Warning",
                    text: "You will be logged out in 5 minutes due to inactivity.",
                    icon: "warning",
                    confirmButtonText: "OK"
                });
            }, warningTime);
    
            inactivityTimer = setTimeout(() => {
                Swal.fire({
                    title: "Logged Out",
                    text: "You have been logged out due to inactivity.",
                    icon: "info",
                    showConfirmButton: false,
                    timer: 2000
                }).then(() => {
                    window.location.href = "{% url 'account:logout' %}";
                });
            }, logoutTime);
        }
    
        ['mousemove', 'keydown', 'click', 'scroll'].forEach(evt => {
            document.addEventListener(evt, resetTimers, false);
        });
    
        resetTimers(); // initialize on load
      })();
 </script>

Login code in the view.py

def user_login2(request):
    try:
        if request.method == 'POST':
            form = LoginForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                username=cd['username']
                password=cd['password']
                user = authenticate(request, username=username, password=password)
                if user is not None:
                    if user.is_active:
                        login(request, user)
                        # Redirect to home page which contains all users Initiatives.
                        return redirect("/en/home")
                    else:
                        # Return an 'invalid login' error message.
                        messages.error(request, 'You do not have access to EnhanceX, contact the administrator!!!')
                        return redirect("/login_page")
        else:
            form = LoginForm()
    except Exception as e:
         print(traceback.format_exc())
         raise
    return render(request, 'account/login.html', {'form': form})

Any help will be greatly appreciated

1 Like

What are you doing when the problem happens? What URLs? What activity are you performing.

And show the full traceback of the error from the terminal/logs.

2 Likes

After I implemented the logout feature after 30 minutes of inactivity, I got the errors below when I try to login using this link

http://127.0.0.1:8000/en/login_page
Internal Server Error: /en/login_page
Traceback (most recent call last):
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 2117, in get_prep_value
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'SimpleLazyObject'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/bejide/EnhanceX/account/views.py", line 87, in user_login2
    return render(request, 'account/login.html', {'form': form})
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/shortcuts.py", line 25, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/template/base.py", line 169, in render
    with context.bind_template(self):
  File "/usr/lib/python3.10/contextlib.py", line 135, in __enter__
    return next(self.gen)
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/template/context.py", line 254, in bind_template
    context = processor(self.request)
  File "/home/bejide/EnhanceX/Fit4/context_processors.py", line 6, in global_function
    Top5Initiatives = Initiative.objects.filter(author=request.user).order_by('-Created_Date').order_by("?") [:10]
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/db/models/manager.py", line 87, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/db/models/query.py", line 1476, in filter
    return self._filter_or_exclude(False, args, kwargs)
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/db/models/query.py", line 1494, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/db/models/query.py", line 1501, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1613, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1645, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1559, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1389, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/db/models/lookups.py", line 30, in __init__
    self.rhs = self.get_prep_lookup()
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/db/models/fields/related_lookups.py", line 156, in get_prep_lookup
    self.rhs = target_field.get_prep_value(self.rhs)
  File "/home/bejide/EnhanceX/.venv/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 2119, in get_prep_value
    raise e.__class__(
TypeError: Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f9ac19ef6d0>>.
[05/Apr/2025 21:18:50] "GET /en/login_page HTTP/1.1" 500 161641

@philgyford

Thank you very much for your response.

When you asked me to show the full traceback of the error from the terminal/logs. As I was going through it I saw a line

File "/home/bejide/EnhanceX/Fit4/context_processors.py", line 6, in global_function
    Top5Initiatives = Initiative.objects.filter(author=request.user).order_by('-Created_Date').order_by("?") [:10]

It reminded me I created a context_processors.py file in my application and since it is a global function, it gets called earlier in the process and since the user has been logged out, django sees it as an AnonymousUser. so the line began to fail.

I then changed the code to test if the user was authenticated:

if request.user.is_authenticated:
        Top5Initiatives = Initiative.objects.filter(author=request.user).order_by('-Created_Date').order_by("?") [:10]

And when I did this the error was over.

Thank you very much, I greatly appreciate your response.

Well done!

Yes, that’s the first thing to do with an error - look up through the trace to find the first part that’s your code - that’s where the error occurred.

1 Like