How to create or register User using django-tastypie API programmatically?

Elvin R. picture Elvin R. · Jan 17, 2012 · Viewed 9.9k times · Source

My code below kinda works, it creates the User object and saves but it doesn't save the password:

class CreateUserResource(ModelResource):
    class Meta:
        allowed_methods = ['post']
        object_class = User
        authentication = Authentication()
        authorization = Authorization()
        include_resource_uri = False
        fields = ['username']

    def obj_create(self, bundle, request=None, **kwargs):
        try:
            bundle = super(CreateUserResource, self).obj_create(bundle, request, **kwargs)
        except IntegrityError:
            raise BadRequest('That username already exists')
        return bundle

If I add 'password' to the Meta fields then it does save the raw password but not hashing it. What am I doing wrong?


So this is what worked for me:

def obj_create(self, bundle, request=None, **kwargs):
    username, password = bundle.data['username'], bundle.data['password']
    try:
        bundle.obj = User.objects.create_user(username, '', password)
    except IntegrityError:
        raise BadRequest('That username already exists')
    return bundle

Answer

Aldarund picture Aldarund · Jan 18, 2012

When creating a user you need either use method set_password user.set_password(bundle.data.get('password')) or use a create_user method of User object.

user = User.objects.create_user(bundle.data.get('username'), bundle.data.get('email'), bundle.data.get('password'))

So something like this would work for you:

def obj_create(self, bundle, request=None, **kwargs):
    try:
        bundle = super(CreateUserResource, self).obj_create(bundle, request, **kwargs)
        bundle.obj.set_password(bundle.data.get('password'))
        bundle.obj.save() 
    except IntegrityError:
        raise BadRequest('That username already exists')
    return bundle