Hi All,
Sorry for the slow reply; I quickly went with the "second endpoint" approach which delayed taking on the real problem.
On Sunday, 2 December 2012 00:50:14 UTC+1, Rod Afshar wrote:
Just wanted to share how I went about tackling this.
I've bashed a working solution together combining Tom and Rod's approach.
I've added a ?set_password query parameter to the UserList view that switches the serializer on POSTs:
class UserList(generics.ListCreateAPIView):
"""
API endpoint that represents a list of users.
"""
permission_classes = (permissions.IsAdminUserOrPostOnly,)
model = User
serializer_class = UserSerializer
def post(self, request, *args, **kwargs):
if request.QUERY_PARAMS.__contains__('set_password'):
self.serializer_class = UserPasswordSerializer
return self.create(request, *args, **kwargs)
(I'm not convinced by the whole query-string switch thing — it's more a work-in-progress sticker.)
The UserPasswordSerializer looks like this:
class UserPasswordSerializer(serializers.HyperlinkedModelSerializer):
fields = ('url', 'username', 'email','password')
def convert_object(self, obj):
"""Remove password field when serializing an object"""
del self.fields['password']
return super(UserPasswordSerializer, self).convert_object(obj)
def restore_object(self, attrs, instance=None):
if instance: #Update
user = instance
user.username = attrs['username']
user.email = attrs['email']
else:
user = User(username=attrs['username'], email=attrs['email'],
is_staff=False, is_active=True, is_superuser=False)
user.set_password(attrs['password'])
# note I don't save() here. The view's create() does that.
return user
As I say, it's all work in progress (and all entirely derivative) but it works with auth.User and (thus far) has the desired behaviour. I'll continue working on it.