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.
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.