Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include user in the signal kwargs #439

Open
martini97 opened this issue Dec 1, 2020 · 4 comments
Open

Include user in the signal kwargs #439

martini97 opened this issue Dec 1, 2020 · 4 comments

Comments

@martini97
Copy link

Describe the problem

Hi, is there a way to include the admin user in the kwargs of the config_updated signal? I understand that it's possible to update from the command line (it would be nice to have a flag blocking this as well), but when changed from the admin page it would be nice to have this info to allow for accountability.

@oubeichen
Copy link

+1

1 similar comment
@yuri-truth
Copy link

+1

@Mogost
Copy link
Member

Mogost commented Jul 12, 2024

Pull request welcome

@pchatzou pchatzou assigned pchatzou and unassigned pchatzou Nov 26, 2024
@shifenhutu
Copy link

here is my code, its work:

yourapp/middleware.py

# yourapp/middleware.py
import threading

_thread_locals = threading.local()

class CurrentUserMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        
    def __call__(self, request):
        # save the user
        _thread_locals.user = request.user if hasattr(request, 'user') else None
        response = self.get_response(request)
        # clear
        _thread_locals.user = None
        return response

def get_current_user():
    return getattr(_thread_locals, 'user', None)

settings.py

# settings.py
MIDDLEWARE += [
    'yourapp.middleware.CurrentUserMiddleware',
    # ...
]

yourapp/signals.py

# yourapp/signals.py
from django.dispatch import receiver
from constance.signals import config_updated
from .middleware import get_current_user

@receiver(config_updated)
def constance_updated(sender, key, old_value, new_value, **kwargs):
    user = get_current_user()
    username = user.username if user and user.is_authenticated else '未知用户'
    print(f"用户 '{username}' 将配置项 '{key}' 从 '{old_value}' 修改为 '{new_value}'")

yourapp/apps.py

# yourapp/apps.py
from django.apps import AppConfig


class ConfigManagerConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'yourapp'


    def ready(self):
        import yourapp.signals

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants