开发者

Getting remote ip and model field name in signals

How to get remote ip and fields name in signals ?

I have tried using def ModelChangeLogger(sender, request, **Kwargs): but it throws error message takes only one argument. The code:

signals.py

   def ModelChangeLogger(sender, **Kwargs):
      if str(sender._meta) == str(models.DBLogEntry._meta):
        return

      log_time = datetime.datetime.now()
      log_table_name = sender._meta.object_name
      log_instance = Kwargs['instance']
      log_ip = '0.0.0.0' **####开发者_Go百科### Remote ip #########**
      log_change_type = ''
      if 'created' in Kwargs:
        log_change_type = Kwargs['created'] and 'Creation' or 'Updating'
      else:
        log_change_type = 'Deleting'

      models.DBLogEntry.objects.create(
          log_time=log_time,
          log_table_name=log_table_name,
          log_instance=log_instance,
          log_change_type=log_change_type
      )

__init__.py

from django.db.models.signals import post_save
from django.db.models.signals import pre_save
from django.db.models.signals import post_delete

from myapp.tracker.signals import ModelChangeLogger

pre_save.connect(ModelChangeLogger)
post_save.connect(ModelChangeLogger)
post_delete.connect(ModelChangeLogger)

How to get remote_add and field names from there?


It is not recommendable to have a signal handler expecting a request object due to the fact that a model save might be triggered without having a request coming from a web browser (eg. if you simply do it through the shell) or call model.save() somewhere else in your code!

You could either make your own custom signal that gets send from the views that modifiy your model or call the logging method yourself in your views.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜