Manage tow Signals in two different apps in Django

Question:

i have two Django applications, blogApp and accounts, when i created a signal file for blogapp that can slugify title after saving the model into database, this works perfectly.
But when i added the second signal file to accounts that can create profile to the user when he finished his registration, it shows me this error:
Post matching query does not exist., and when i check the admin section, i can see the profile has been successfully created.

PostModel in blogApp application:
PostModel in blogApp application

Signals in blogApp application:
Signals in blogApp application

ProfileModel in accoounts application:
Profile Model in accounts app

Signals in accounts application:
Signals in accounts app

So, how can i create the user profile without indexing to Post signals.
Because what i’m thinking is the two signals of two apps is activating after the user press register.

Asked By: Hardy

||

Answers:

I think, your problem is with the sender you have set.
You want to make a specific action about a Post instance,but you set User as sender ?
So in your receive function, you try to get a Post instance with as id the id of the user provided as isntance.

@receiver(post_save, sender=Post)
def slugify_title_model_field(sender, instance, created, **kwargs):
    if created:
        post_to_slugify = Post.objects.get(id=instance.id)
        post_to_slugify.title = slugify(post_to_slugify.title)
        post_to_slugify.slug = slugify(post_to_slugify.title)
        post_to_slugify.save()

Of course, you have to remove the post_save.connect... write after this code.

But for this case, I advise you to overload the save function of your model, it is there for that, and it would be much more logical to put this function in a model because it directly concerns the instance being saved. I use signals to deal with cases external to the model itself in general

Answered By: Lucas Grugru
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.