Reputation: 450
I'm trying to create a new user using DRF. The code actually creates the user but I get a 500 error saying that user is not JSON serializable. I would like to get rid of this error. Here are how my files look
views.py
class UserCreateAPIView(ModelViewSet):
queryset = EndUser.objects.all()
serializer_class = NewUserSerializer
permission_classes = (AllowAny,)
serializers.py
class NewUserSerializer(serializers.ModelSerializer):
class Meta:
model = models.EndUser
fields = ('id', 'first_name', 'last_name', 'email', 'title', 'user_type', 'packages', 'practice_area',
'office_phone', 'level', 'companies', 'country', 'password', 'firm', 'sectors', 'verticals', 'user_ptr')
def save(self, *args, **kwargs):
user = super().save(*args, **kwargs)
user.set_password(user.password)
user.save()
urls.py
router.register('new-user', views.UserCreateAPIView)
Enduser inherits User. Would anyone have any ideas on how to fix this?
Upvotes: 1
Views: 1553
Reputation: 476493
You should remove the user_ptr
field which is, If I understood it correctly the OneToOneField
Django constructed for its model inheritance:
class NewUserSerializer(serializers.ModelSerializer):
class Meta:
model = models.EndUser
fields = ('id', 'first_name', 'last_name', 'email', 'title'
, 'user_type', 'packages', 'practice_area'
, 'office_phone', 'level', 'companies', 'country'
, 'firm', 'sectors', 'verticals', 'password'
) # no user_ptr
extra_kwargs = {'password': {'write_only': True}}
def save(self, *args, **kwargs):
user = super().save(*args, **kwargs)
user.set_password(user.password)
user.save()
While Django will hash passwords, it is not a good idea to mark the password
as a field that can be read. It means that you will retrieve the password hash, and although that might still require a lot of computational effort to obtain the real password, it is still not a good idea.
Upvotes: 2