Mongoengine signals listens for all models
<p>I have setup <code>django</code> project with <code>mongoengine</code> for using mongodb with django. I have created 2 models and they work fine, but when I use signal listener for one model It also listens for another model, so how can I keep the signals bound to their models?</p>

<p>Here's my code for model User:</p>

<pre class="lang-py prettyprint-override"><code>from mongoengine import *
from mongoengine import signals
from datetime import datetime


class User(Document):
    uid = StringField(max_length=60, required=True)
    platform = StringField(max_length=20, required=True)
    index = StringField(max_length=80)
    last_updated = DateTimeField(required=True, default=datetime.now())

    meta = {
        'collection': 'social_users'
    }


def before_save(sender, document, **kwargs):
    if document.platform and document.uid:
        document.index = document.platform+'/'+document.uid

signals.pre_save.connect(before_save)
</code></pre>

<p>Here's another model <code>Error</code></p>

<pre class="lang-py prettyprint-override"><code>from mongoengine import *
from datetime import datetime


class Error(Document):
    call = DictField(required=True)
    response = DictField(required=True)
    date = DateTimeField(default=datetime.now(), required=True)

    meta = {
        'collection': 'errors'
    }
</code></pre>

<p>Here's the file which I'm using to test the code:</p>

<pre class="lang-py prettyprint-override"><code>from src.social.models.error import Error
from src.social.models.user import User

error = Error.objects.first()

print(error.to_json())
</code></pre>

<p>But it doesn't work, throws the following error:</p>

<pre><code>AttributeError: 'Error' object has no attribute 'platform'
</code></pre>

<p>Please help me with this, thanks.</p>

<p>I figured out a way to bind signals for particular models, here's the code how I did it:</p>

<pre class="lang-py prettyprint-override"><code>from mongoengine import *
from mongoengine import signals
from datetime import datetime


class User(Document):
    uid = StringField(max_length=60, required=True)
    platform = StringField(max_length=20, required=True)
    index = StringField(max_length=80)
    last_updated = DateTimeField(required=True, default=datetime.now())

    meta = {
        'collection': 'social_users'
    }

    @classmethod
    def pre_save(cls, sender, document, **kwargs):
        if document.platform and document.uid:
            document.index = document.platform+'/'+document.uid

signals.pre_save.connect(User.pre_save, sender=User)
</code></pre>

<p>Hope this helps the people who face the same problem.</p>

python django mongodb mongoengine