Thanks to Alon Swartz for this.
A snippet to create a user profile the first time it is accessed. It looks better having
user.profile rather than
user.get_profile() as well.
Please note: The
user.profile is not cached, unlike
user.get_profile, so the database query will run multiple times, this may not matter on your website but bare it in mind
from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.ForeignKey(User, unique=True) website = models.URLField() User.profile = property(lambda u: Profile.objects.get_or_create(user=u))
User.profile as you can see above, runs
get_or_create on the