Django How to send a post_save signal when updating a user?

after reading the documents

https://docs.djangoproject.com/en/dev/topics/signals/

I created this in my signal.py file:

from django.db.models.signals import post_save from django.dispatch import receiver from models import User from models import Story @receiver(post_save, sender=User) def create_initial_story(sender,instance, signal, created, **kwargs): print "helloooo!" if created: Story(user = instance, title = 'Random Stories', description="Random stories", is_closed = False, is_random = True).save() 

which, from what I read, was all that I thought was necessary to do in order to send a message. Well, this is to create a new user (I use the django-registration structure). However, nothing is sent (well, the receiver method, I do nothing). I also removed the "sender = User" parameter in the @receiver annotation - leaving

 @receiver(post_save) 

but it did not help. Nothing is output to the console, new data is not saved ... do I need to send a signal from the user when the user is saved ?? If so, how do I do this? I use django-registration, so I have UserProfile defined ... what do I mean, where (in which file / method) would I tell the user to send a signal?

+4
source share
2 answers

You must import signals.py somewhere to run it. For example, in models.py .

+9
source

First, they are called "decorators." Annotations are something else in Django, so it's best not to confuse the terminology there.

The post_save signal post_save called, as the name implies, after each save. Specifying sender limits the receiver to only post_save signals sent to save this particular model. If you leave it, your receiver will be called when any model is saved, which is certainly not what you want.

Your problem is that your receiver, in every sense and purpose, does not exist. Django does not automatically import signals.py import for you, so it has never been seen. The only way to see it is to import it somewhere that Django can look at, for example models.py (like @DrTyrsa).

However, if you do, you will get a circular import error, since you are already importing models.py into signal.py. Thus, you can simply put your signal code directly in models.py or find somewhere else to import it; __init__.py may work, but I usually just always put my signals in models.py and call it day.

+6
source

Source: https://habr.com/ru/post/1414144/


All Articles