Tal Peretz
Tal Peretz

Reputation: 515

Create model after group has been created django

I need to create an instance of my model every time a new group has been created in the admin panel.

I read some information about signals, but i can't figured it out at all.

Thank you very much

Upvotes: 1

Views: 95

Answers (1)

stalk
stalk

Reputation: 12054

models.py with your model:

from django.db import models
from django.contrib.auth.models import Group
from django.db.models.signals import post_save


class YourModel(models.Model):
    name = models.CharField('name', max_length=50)
    group = models.ForeignKey(Group)
    # ...

    @classmethod
    def create_after_group(cls, sender, instance, created, **kwargs):
        if created:
            group_created = instance
            m = cls(name="Some name", group=group_created)
            m.save()


post_save.connect(YourModel.create_after_group, sender=Group)

Upvotes: 3

Related Questions