0

I am using django-registration. I have created a class named "Statistics" with a one-to-one relation with each instance of the class User.

Every time a new User is created via the /accounts/register page, I would like to be able to create a new instance of the class "Statistics" and associate it to the just created User.

My question is, where should I have to write the code to do that? Where should I place the code to be executed each time a new User is created? Something along the lines of:

s = Statisics ( comments = 0, thanked = 0, user = UserThatWasJustCreated)

Thanks.

Xar
  • 7,572
  • 19
  • 56
  • 80

2 Answers2

3

As indicated by Josh, you should attach your code to a signal, except I would consider attaching it to Django's post_save signal if you need your code run even when a User is created outside django-registration.

In that case, it should be something like:

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

def create_statistic(sender, *args, **kwargs):
    if kwargs.get('created'):
        s = Statisics( comments=0, thanked=0, user=kwargs['instance'])

post_save.connect(create_statistics, sender=User)

You can place that code after your Statistics model definition.

Gonzalo
  • 4,145
  • 2
  • 29
  • 27
  • Thank you Gonzalo for your detailed answer. This is just what I was looking for. – Xar Dec 19 '12 at 17:19
1

Check out the custom signals that Django-Registration makes available: http://docs.b-list.org/django-registration/0.8/signals.html. I think one of these will do the job for you.

Josh
  • 12,896
  • 4
  • 48
  • 49
  • Thank you Josh for your prompt response. You were absolutely right pointing me in that direction. – Xar Dec 19 '12 at 17:20