I'm coding a REST API with Django REST framework. The API will be the backend of a social mobile app. After following the tutorial, I can serialise all my models and I am able to create new resources and update them.
I'm using AuthToken for authentication.
My question is:
Once I have the /users
resource, I want the app user to be able to register. So, is it better to have a separate resource like /register
or allow anonymous users to POST to /users
a new resource?
Also, some guidance about permissions would be great.
The simplest solution, working in DRF 3.x:
No need for other changes, just make sure that unauthenticated users have the permission to create a new user object.
write_only_fields
will make sure passwords (actually: their hash we store) are not displayed, while the overwrittencreate
method ensures that the password is not stored in clear text, but as a hash.Django REST Framework 3 allow override
create
method in serializers:Serialized fields for classes inherited from
ModelSerializer
must be declared patently inMeta
for Django Rest Framework v3.5 and newest.File api.py:
@cpury above suggested using
write_only_fields
option. This however did not work for me in DRF 3.3.3In DRF 3.0 the
write_only_fields
option on ModelSerializer has been moved to PendingDeprecation and in DRF 3.2 replaced with a more generic extra_kwargs:extra_kwargs = {'password': {'write_only': True}}
I went ahead and made my own custom view for handling registration since my serializer doesn't expect to show/retrieve the password. I made the url different from the /users resource.
My url conf:
My view:
I may be wrong, but it doesn't seem like you'll need to limit permissions on this view since you'd want unauthenticated requests ...
A little late to the party, but might help someone who do not want to write more lines of code.
We can user the
super
method to achieve this.I updated Cahlan's answer to support custom user models from Django 1.5 and return the user's ID in the response.