django - Django signals not working for my directory structure
问题描述
I am trying to implement signals for my app and my directory structure looks like this
- src
- utility_apps
__init__.py
- posts
- migrations
- static
- templates
admin.py
views.py
apps.py
signals.py
models.py
__init__.py
......
static
manage.py
......
Here posts
is my app and the signals.py
is inside its folder, But my signals aren't working.
I have defined my signal code as -
from .models import Post
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Post)
def give_group_owner_permission(sender, instance, created, **kwargs):
print("coming to signal")
if created:
print("created")
But it doesn't work. In my apps.py
I have changed the ready function as
class Post(AppConfig):
name = 'post'
def ready(self):
import utility_apps.posts.signals
I have even tried importing posts.signal
in the ready function. What I am doing wrong here, please help
My installed apps look like below
INSTALLED_APPS = [
'utility_apps.posts',
'mainapp',
.....
]
解决方案
以下解决方案对我有用。
我必须做的第一个更改是在我的应用程序文件中添加一个default_app_config
值__init__.py
posts
default_app_config = 'utility_apps.posts.apps.PostsConfig'
然后我不得不改变PostsConfig
班级
class PostsConfig(AppConfig):
name = 'utility_apps.posts'
def ready(self):
import utility_apps.posts.signals
基本上我必须改变两件事 -
posts
默认设置的名称- 更改就绪函数并将我的信号导入其中
它对我有用。或者,我也可以在我安装的应用程序中包含我的 PostsConfig。
推荐阅读
- python - 如何优化我的 BFS 实施?
- azure-web-app-service - 将 AppServices 的访问权限锁定到仅 Azure Front Door
- swift - 主线程和 Collectionview.reloadData()
- javascript - 在二维数组上运行 .map() 后如何用数据填充列
- r - 计算列中字典单词的频率并生成新的“dictfreq”列
- python-3.x - CVXPY 无法安装:找不到文件“setup.py”
- reactjs - 使用 Chai 测试组件时显示错误 Cannot read property 'indexOf' of undefined ,如何解决?
- angular - 为什么 ngModelChange 不能正常工作?
- excel - Excel VBA - Sharepoint 上的另存为模板不会创建新文档
- javascript - 为什么我的 .indexOf 不读取字符串中字符的位置