1

I am building a DRF project and have enabled user authentication and registration using django-allauth and django-rest-auth. A new user is registered by providing username, email, password1 and password 2.

I want to create a user profile when a user is created, however he would have to enter anything related to profile while registration. User can edit this profile afterwards, whenever he wants. My user profile model:

class Profile(models.Model):
    user = models.OneToOneField(User, blank=True, on_delete=models.CASCADE, )
    name = models.CharField(max_length=50, blank=True, )
    age = models.IntegerField(blank=True, )
    ...
    ...

and in serializers.py I have:

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = '__all__'

I saw some posts which added following methods to Profile model:

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

with them, user was created but not the profile, and I got error IntegrityError: (1048, "Column 'age' cannot be null")

What is the most elegant way of creating, and updating such a profile?

Thinker
  • 5,326
  • 13
  • 61
  • 137
  • about that error age cannot be null, may be you can do in age property, null = True instead of blank = True – anupam691997 Apr 16 '18 at 11:41
  • Thanks for your comment, I tried your suggestion but it then throws No connection could be made because the target machine actively refused it error, however profile and user both are created – Thinker Apr 16 '18 at 11:55
  • Which also I fixed by adding EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' – Thinker Apr 16 '18 at 11:57

1 Answers1

0

to eliminate IntegrityError change

from :

user = models.OneToOneField(User, blank=True, on_delete=models.CASCADE, )

to:

user = models.ForeignKey(User, blank=True, on_delete=models.CASCADE, ) 

however, i don't know if that relationship suit your specification

Usitha Indeewara
  • 870
  • 3
  • 10
  • 21
Tamar
  • 1
  • 1