Using instance data in signal handler django

Gaurav Source

Can I user model instance data in signal handler to create different profile models as per user type? I tried it but its not working and only one kind of profile is being created the Student profile even if the user_type is institute.

In models.py

class User(AbstractUser):
type_choices = (
    ('Student', 'Student'),
    ('Institute', 'Institute')
)
user_type = models.CharField(max_length=2,choices=type_choices,default='Student')




class Profile(models.Model):
    bio = models.CharField(max_length = 200, null = True, blank = True)
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    birth_date = models.DateField(null=True, blank=True)
    image = models.ImageField(upload_to=user_image_path, blank=True)

class Iprofile(models.Model): 
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    date_of_incorporation = models.DateField(null=True, blank=True)
    logo = models.ImageField(upload_to=user_image_path, blank=True)


@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        if instance.user_type == "Student":
            Profile.objects.create(user=instance)
            instance.profile.save()
        elif instance.user_type =="Institute":
            Iprofile.objects.create(user=instance)
            instance.iprofile.save()

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def save_user_profile(sender, instance, **kwargs):
    if instance.user_type == "Student":
        instance.profile.save()
    elif instance.user_type == "Institute":
        instance.iprofile.save()

In forms.py

user_type_choices = (
    ('Student', 'Student'),
    ('Institute', 'Institute'),
)

class SignUpForm(forms.Form):
    user_type = forms.ChoiceField(choices = user_type_choices)

    def signup(self, request, user):
        user.user_type = self.cleaned_data['user_type']
        user.save()
pythondjangosignalsinstancereceiver

Answers

comments powered by Disqus