首页 > 解决方案 > 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',
     .....
]

标签: djangodjango-signals

解决方案


以下解决方案对我有用。

我必须做的第一个更改是在我的应用程序文件中添加一个default_app_config__init__.pyposts

default_app_config = 'utility_apps.posts.apps.PostsConfig'

然后我不得不改变PostsConfig班级

class PostsConfig(AppConfig):
    name = 'utility_apps.posts'

    def ready(self):
        import utility_apps.posts.signals

基本上我必须改变两件事 -

  1. posts默认设置的名称
  2. 更改就绪函数并将我的信号导入其中

它对我有用。或者,我也可以在我安装的应用程序中包含我的 PostsConfig。


推荐阅读