Home > database >  Manage tow Signals in two different apps in Django
Manage tow Signals in two different apps in Django

Time:10-11

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.

CodePudding user response:

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.

class Post(models.Model):
    ...

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)

        super().save(*args, **kwargs)


  • Related