简体   繁体   中英

How to do user registration in Django REST framework api

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

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
    [...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM