0

I was looking for solution for my problem here, but it didnt solve my problem.

I want to create user's profile while their signing up. To signup I use CreateView

class UserRegisterView(generic.CreateView):
    form_class = SignUpForm
    template_name = 'registration/register.html'
    success_url = reverse_lazy('login')

    #this method doesn't work and I get 
    # `Profile.user" must be a "User" instance`

    def form_valid(self,form):
        Profile.objects.create(user=self.request.user)

My Profile model looks like:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    #rest of fields like bio, social urls etc

My main point is to automatically create user's profile when their create their account. What is the best way to solve this?

Frendom
  • 508
  • 6
  • 24
  • 2
    Best way? I would suggest going with signals as mentioned here https://stackoverflow.com/a/57349227/4626254 – Underoos Jan 05 '21 at 12:06
  • 1
    Does this answer your question? [Django - Create user profile on user creation](https://stackoverflow.com/questions/11488974/django-create-user-profile-on-user-creation) – SAI SANTOSH CHIRAG Jan 05 '21 at 12:08

1 Answers1

2

I will suggest to avoid using signals, since you have a form.

self.request.user will return an user object only when an user is logged in using any form of authentication (Session, token etc.)

def form_valid(self,form):
    user = form.save()
    Profile.objects.create(user=user)
    return super(UserRegisterView, self).form_valid(form)
Agawane
  • 173
  • 1
  • 8