[Django]-Django populate db with some data when new user is created

5👍

What you’re looking for is Django’s signals framework.

from django.db.models.signals import post_save
from django.dispatch import receiver

from django.contrib.auth.models import User, Group
from my_app import Category, Feed

@receiver(post_save, sender=User)
def init_new_user(instance, created, raw, **kwargs):
    # raw is set when model is created from loaddata.
    if created and not raw:
        instance.groups.add(
            Group.objects.get(name='new-user-group'))

        Category.objects.create(
            name="Default", user=instance)

        Feed.objects.create(
            user = instance,
            name = "%s's Feed" % instance.first_name,
            ....
        )

REF: https://docs.djangoproject.com/en/1.5/topics/signals/

👤Thomas

1👍

There are at least two ways you can handle populating additional models with data when creating a new user. This first one that comes to mind is a post_save signal:

from django.db.models.signals import post_save
from django.dispatch import receiver

from your_app.models import Category, Feed

@receiver([post_save, post_delete], sender=Coupon)
def add_user_data(sender, **kwargs):
    user = kwargs.get('instance')

    try:
        category, category_created = Category.objects.get_or_create(user=user,
            defaults={'name': 'Some Value', 'user': user})

        try:
            feed, feed_Created = Feed.objects.get_or_create(user=user,
                category=category, defaults={'url': 'some-url',
                    'name': 'some-name', 'description': 'some-desc',
                    'category': category, 'user': user})
        except MultipleObjectsReturned:
            pass
    except MultipleObjectsReturned:
        pass

This code would execute any time an instance of User is saved, but only create the additional records if they don’t already exist for that user.

Another way would be to override the save() method on a form for the User. If you also need this functionality in Django admin, you would need to un-register the built-in UserAdmin and register your own UserAdmin class to leverage the custom form.

Leave a comment