I have a requirement to write a DB row when a user logs in. The following code is in models.py (at end of file, after model definitions);
models.py
from django.contrib.auth.signals import user_logged_in
from utils import *
def rec_login(sender, request, user, **kwargs):
u_audit('some text here', user)
user_logged_in.connect(rec_login)
There’s a utilities module which is imported in modules.py. The following code is called in utils.py from the above function;
utils.py
from app.models import *
def u_audit(msg,u):
ua=UserLog(action=msg, user=u, actiontime=datetime.now())
ua.save()
I’m reusing the u_audit() function in several other places (post-login).
When a user logs in, I get a NameError for the UserLog object (i.e. it looks like the model definitions can’t be accessed by the signal callback function).
The UserLog object referred to above is just a simple models.Model.
Anyone know what I’m missing?
I’ve tried putting a simple file write in the callback function in models.py and tried the same thing in the u_audit() function. instead and that works fine, so I know it’s being called properly. I’ve got other signal callback functions registered (all post-login) and they’re using models and working fine.
Not a circular import? Utils refers to models and models to utils – it will not work. Please change utils.py to:
But also something like that suggest that maybe models.py is good place for u_audit and you should just move it there.