1
votes

I have searched the whole web and cant find any satisfying answer I have changed my user model by adding some custom fields

So now i got 'username', 'password', 'email', 'first_name', 'last_name', 'phonenumber', 'address'

instead of

'username', 'password', 'email', 'first_name', 'last_name', --- (these are default)---


This is my models.py

from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User

class userinformation(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phonenumber = models.CharField(max_length=100)
    address = models.CharField(max_length=200)
    class Meta:
        verbose_name_plural = "User Information"
    def __str__(self):
        return str(self.user)+' - '+self.phonenumber+' - '+self.address

Im trying to make a Django REST framework api on which i can post

        'username',
        'password',
        'email',
        'first_name',
        'last_name',
        'phonenumber',
        'address'

And register user with these details what should i add in my veiws.py and serializers.py

1
can you provide serializer and view?Marin

1 Answers

2
votes

Adding these other fields comes from manipulating the serializer. You could do something like this to expose those fields if you add field related_name='user_information' to your model definition:

user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_information')

Then you create a serializer like:

class UserSerializer(serializers.HyperlinkedModelSerializer):

    phonenumber = serializers.CharField(source='user_information.phonenumber')
    address = serializers.CharField(source='user_information.address')

    class Meta:
        model = User

        fields = ('username', 'password', 'email', 'first_name', 'last_name',
            'phonenumber', 'address')

and instantiate that serializer in your view:

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    [...]