3

How can I populate the following tables with some default / initial data, every-time new user is created ? I know about this https://docs.djangoproject.com/en/dev/howto/initial-data/, but this works only when I create models. Here I want to insert some default entries when new user is created.

Additionally, when I create a new user how can I add him to a given group with a static group id automatically ?

models.py

from django.db import models
from django.contrib.auth.models import User

class Category(models.Model):
    name = models.CharField(max_length=50)
    user = models.ForeignKey(User)

class Feed(models.Model):
    url = models.URLField()
    name = models.CharField(max_length=50)
    created = models.DateTimeField(auto_now_add=True)
    description = models.TextField(blank=True)
    category = models.ForeignKey(Category)
    user = models.ForeignKey(User)

views.py

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm1(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/accounts/login")
    else:
        form = UserCreationForm1()
    return render(request, "registration/signup.html", {
        'form': form,

    })

forms.py

class UserCreationForm1(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ('username', 'email')

Many thanks!

Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
sikor
  • 143
  • 2
  • 10
  • searching google and this forum is what I did so far but I can't figure it out. I'm thinking I would have to add it somewhere in the UserCreationForm1 ? – sikor Oct 17 '13 at 11:52
  • but each time a user is created, initial data will be stored for him/her if you do default https://docs.djangoproject.com/en/dev/ref/models/fields/#default.I am not sure if that is what you want though. About saving the user to a group, you can do something like this http://stackoverflow.com/questions/6288661/adding-a-user-to-a-group-in-django/6288863#6288863, maybe extend the user model and add this method? – tamara Oct 17 '13 at 12:01

2 Answers2

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/

Daniel
  • 3
  • 2
Thomas
  • 11,757
  • 4
  • 41
  • 57
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.

Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144