Sunday, March 26, 2017

Re: How to create a new user with django rest framework and custom user model

I think you have a few errors in your code.

In views.py you write:
        User.objects.create_user(
            serialized.save()
        )

serialized.save() is probably calling User.objects.create - which you shouldn't do. If you want to create a user the way you are doing you will need to override the default create_user method on the User model. Add support for handling the password1 and password2 fields and then add support for the first_name and last_name fields.

Then you can override the create method on the serializer class like this:
def create(self, validated_data):
"""
Override default implementation of the create method. Make sure user gets password.

:param validated_data: the validated data sent to the method

:return: the newly created user if successful
"""
if self.is_valid(True):
return User.create_user(validated_data.get("email"), validated_data.get("password"),
validated_data.get("first_name"), validated_data.get("last_name"))

Regards,

Andréas

2017-03-26 18:23 GMT+02:00 Aamu Padi <aamupadi@gmail.com>:
I have a custom user model and I am using django-rest-framework to create API

models.py:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
        unique=True,
        max_length=254,
    )
    first_name = models.CharField(max_length=15)
    last_name = models.CharField(max_length=15)
    mobile = models.IntegerField(unique=True)
    date_joined = models.DateTimeField(default=timezone.now)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

serializers.py:

class UserSerializer(serializers.ModelSerializer):
    password1 = serializers.CharField(write_only=True)
    password2 = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'mobile', 'password1', 'password2')

views.py:

@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
    serialized = UserSerializer(data=request.data)
    if serialized.is_valid():
        User.objects.create_user(
            serialized.save()
        )
        return Response(serialized.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

However, when I try to create a new user I am getting this error:

Got a TypeError when calling User.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to User.objects.create(). You may need to make the field read-only, or override the UserSerializer.create() method to handle this correctly.

This maybe because there's no password1 or password2 fields in the User model. But so, how can I create an API to create a new user using django-rest-framework?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAHSNPWtWmifpo6BuWQmp3-Y-pXyJAPBELf90MmeWLQBB9nGmyw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAK4qSCe5CqajAZs7wOdoRh7-yzj%3DZVxXpbDRas3znndubymddA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment