marek
marek

Reputation: 279

Django pre_save signal

I needed to be able to change my model data before it's saved, so I considered using pre_save handler to be the best option:

@receiver(pre_save, weak = False)
def pre_category_save(sender, **kwargs):
    if kwargs['instance'].tags is None:
        kwargs['instance'].tags = kwargs['instance'].__unicode__().replace(' -> ', ', ')

Under the instance key of kwargs I expected to find the actual model instance I'm saving, but instead I got an object of LogEntry class - that's the cause why my function fails returning this error: 'LogEntry' object has no attribute 'tags'. So - how can I fix that? Checking if instance has attribute tags is not a solution, because I always get only logentry object. I can eventually overload Model.save method, though I'd rather not do this.

Upvotes: 1

Views: 3638

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

You haven't specified the model class that's being received by this signal, so it's connected itself to all model saves - including LogEntry. Instead, do this:

 @receiver(pre_save, sender=MyModel, weak=False)
 ...

See the documentation.

Upvotes: 4

Related Questions