[英]Can't refer to models in callback function registered to user_logged_in signal in Django
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中(在文件末尾,在模型定义之后);
models.py 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. 在modules.py中导入了一个实用程序模块。 The following code is called in utils.py from the above function;
上面的函数在utils.py中调用以下代码;
utils.py 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). 我在其他几个地方(登录后)重用了u_audit()函数。
When a user logs in, I get a NameError for the UserLog object (ie it looks like the model definitions can't be accessed by the signal callback function). 当用户登录时,我得到UserLog对象的NameError(即,信号回调函数似乎无法访问模型定义)。
The UserLog object referred to above is just a simple models.Model. 上面提到的UserLog对象只是一个简单的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. 我试过将简单的文件写到models.py的回调函数中,并尝试在u_audit()函数中做同样的事情。 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:
请将utils.py更改为:
def u_audit(msg,u):
from app.models import UserLog
ua=UserLog(action=msg, user=u, actiontime=datetime.now())
ua.save()
But also something like that suggest that maybe models.py is good place for u_audit and you should just move it there. 但是类似的事情也暗示,models.py可能是u_audit的好地方,您应该将其移到那里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.