[Fixed]-Trouble creating a ForeignKey relationship for my UserProfile immediately upon User registration

1👍

The recommended approach to creating a UserProfile when creating a User is to use the post_save signal (here is the docs page explaining what they are).

What basically happens is that when a User model is created (saved for the first time) we create a UserProfile object linked to the User. Like so:

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

@receiver(models.signals.post_save, sender=User)
def create_user_profile(sender, instance=None, created=False, **kwargs):
    if created:
        UserProfile.objects.get_or_create(user=instance)

NOTE: if you use a ForeignKey instead of a OneToOneField you’re going to end up in a situation where an User has several UserProfiles (and thus you can’t do user.user_profile).

The signal will be triggered when you do user.save(), so from there onwards you can just do (assuming you change the field to a OneToOneField):

user.user_profile.interests = interests
user.user_profile.age = age
user.user_profile.save()

to accomplish what you want to do.

0👍

I would begin by changing your relationship to a OneToOneField.

class UserProfile(models.Model):
    age = models.CharField(max_length=100)
    interests = models.TextField(default="")
    user = models.OneToOneField(User)

Next, I would make a post_save signal to generate the new profile.

django.db.models.signals import post_save

def new_user_receiver(sender, instance, created, *args, **kwargs):
    if created:         
        new_profile, is_created = UserProfile.objects.get_or_create(user=instance)

post_save.connect(new_user_receiver, sender=User)
👤jape

Leave a comment