Use custom model extending build-in User model by using djoser for authentication in DRF

30 Views Asked by At

I want to have a separate model named Profile extending User model, so I can store info about the user which is not related to the auth details (email, pass ...) I am using djoser for authentication (token authentication) and I can't make it. I want profile model to have:

user = models.OneToOneField(User,..)
additional_field = models.CharField()

I see some solutions with signals but I think this is too complicated. Is there some easy way.

What I tried:

models.py

from django.contrib.auth.models import User

class Profile(models.Model):
     user = models.OneToOneField(User, on_delete=models.CASCADE)
     custom_field= models.CharField(max_length=100,blank=True)

serializers.py

from djoser.serializers import UserCreateSerializer

class CustomRegistrationSerializer(UserCreateSerializer):
    custom_field= serializers.CharField(write_only=True, allow_blank=True)
    class Meta(UserCreateSerializer.Meta):
        fields = (
            'email',
            'password',
            'custom_field',
            'first_name',
            'last_name',
            'username',
        )

views.py

from djoser.views import UserViewSet
from .serializers import CustomRegistrationSerializer

class CustomUserViewSet(UserViewSet):
    serializer_class = CustomRegistrationSerializer

    def perform_create(self, serializer):
        profile_data = self.request.data.get('custom_field')
        profile = Profile.objects.create(user=user, custom_field=profile_data)
        user = serializer.save()
        user.profile = profile
        user.save()
        

settings.py

DJOSER = {
    'SERIALIZERS': {
        'user_create': 'authapp.serializers.CustomRegistrationSerializer',
    },
}
0

There are 0 best solutions below