Newtt
Newtt

Reputation: 6190

Django create different user profile instances on user signup

I have a Django application where there will be two types of user signups. Consumers and Providers.

class ConsumerProfile(models.Model):
    user = models.OneToOneField(User)
    # Some fields


class ProviderProfile(models.Model):
    user = models.OneToOneField(User)
    # Some fields


def create_user_profile(sender, instance, created, **kwargs):
    if created: # What should the condition be here so that only the correct profile is created
        ConsumerProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

How do I make sure that when a user is created, only the correct profile model instance is created?

Upvotes: 0

Views: 154

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174624

Signals is not the right way to handle this. The correct way is to add this logic in your signup function:

def sign_up(request):
   form = SignupForm(request.POST or None, request.FILES or None)
   if form.is_valid():
      user = User.objects.create_user(form.cleaned_data['usern_name'],
                                      form.cleaned_data['email'],
                                      form.cleaned_data['password'])
      user.save()
      if form.cleaned_data['user_type'] == 'consumer':
         profile = ConsumerProfile()
         profile.some_field = 'some_value'
      if form.cleaned_data['user_type'] == 'provider':
         profile = ProviderProfile()
         profile.some_field = 'some_value'
      if profile:
         profile.user = user
         profile.save()
      user.save()

Upvotes: 2

Ariestinak
Ariestinak

Reputation: 86

You should add a flag to your function and use it to determine the type of the user you want to create. Use an if-block to create different Profiles. Something like this:

def create_user_profile(sender, instance, created, consumerOrProvider, **kwargs):
    if consumerOrProvider == ENUM_CONSUMER:
        ConsumerProfile.objects.create(user=instance)
    elif consumerOrProvider == ENUM_PROVIDER:
        ProviderProfile.objects.create(user=instance)

But why do you want to use a single function for this? Why not use two functions and send the correct request?

Upvotes: 0

Related Questions