Populating django field with pre_save()? Populating django field with pre_save()? python python

Populating django field with pre_save()?


Most likely you are referring to django's pre_save signal. You could setup something like this:

from django.db.models.signals import pre_savefrom django.dispatch import receiverfrom django.template.defaultfilters import slugify@receiver(pre_save)def my_callback(sender, instance, *args, **kwargs):    instance.slug = slugify(instance.title)

If you dont include the sender argument in the decorator, like @receiver(pre_save, sender=MyModel), the callback will be called for all models.

You can put the code in any file that is parsed during the execution of your app, models.py is a good place for that.


@receiver(pre_save, sender=TodoList)def my_callback(sender, instance, *args, **kwargs):    instance.slug = slugify(instance.title)


you can use django signals.pre_save:

from django.db.models.signals import post_save, post_delete, pre_saveclass TodoList(models.Model):    @staticmethod    def pre_save(sender, instance, **kwargs):        #do anything you wantpre_save.connect(TodoList.pre_save, TodoList, dispatch_uid="sightera.yourpackage.models.TodoList")