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