create userprofile
Terkea opened this issue · 1 comments
Terkea commented
I'm using django-rest-auth to handle login and registration. The problem that I stumbled upon is that I'd like to add some custom fields to the default django User model
. I've seen you are covering that on the docs and I've tried replicating their example from here, but when I am making a PUT request for the newly created field from the userprofile I get this error:
RelatedObjectDoesNotExist at /rest-auth/user/
User has no userprofile.
Request Method: PUT
Request URL: http://localhost:8000/rest-auth/user/
Django Version: 2.2.10
Exception Type: RelatedObjectDoesNotExist
Exception Value:
User has no userprofile.
Exception Location: /home/terkea/django_react_template/src/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in __get__, line 415
Python Executable: /home/terkea/django_react_template/src/venv/bin/python
Python Version: 3.6.9
Python Path:
['/home/terkea/django_react_template/src',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/home/terkea/django_react_template/src/venv/lib/python3.6/site-packages']
Server time: Fri, 10 Apr 2020 14:56:41 +0000
This is my model
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
company_name = models.CharField(max_length=100, default=None)
and here's my serializer:
from rest_framework import serializers
from rest_auth.serializers import UserDetailsSerializer
class UserSerializer(UserDetailsSerializer):
company_name = serializers.CharField(source="userprofile.company_name")
class Meta(UserDetailsSerializer.Meta):
fields = UserDetailsSerializer.Meta.fields + ('company_name',)
def update(self, instance, validated_data):
profile_data = validated_data.pop('userprofile', {})
company_name = profile_data.get('company_name')
instance = super(UserSerializer, self).update(instance, validated_data)
# get and update user profile
profile = instance.userprofile
if profile_data and company_name:
profile.company_name = company_name
profile.save()
return instance
I am assuming that the userprofile entry has to be created at the same time when the user is, but I don't know how exactly should I do it.
Terkea commented
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
company_name = models.CharField(max_length=100, default=None)
@receiver(post_save, sender=User)
def create_profile_for_user(sender, instance=None, created=False, **kwargs):
if created:
UserProfile.objects.get_or_create(user=instance)
this solved my problem