[Answer]-Create a User Object with a Call to TastyPie API

1👍

Your Customer model has inherited a custom UserManager manager attribute named objects. It allows you to easily create Customer instances and takes care of the password encryption.

You have to override the obj_create method in your CustomerResource:

class CustomerResource(ModelResource):

    locations = fields.ToManyField('device.resources.LocationResource',
            'location_set', null=True)
    current_location = fields.ToOneField('device.resources.LocationResource',
            'current_location', null=True)
    default_location = fields.ToOneField('device.resources.LocationResource',
            'default_location', null=True)

    class Meta:
        queryset = Customer.objects.all()
        resource_name = 'customers'
        validation = CleanedDataFormValidation(form_class=RegistrationForm)
        list_allowed_methods = ['get', 'post']
        detail_allowed_methods = ['get', 'put', 'patch', 'delete']
        authorization = Authorization()
        excludes =['is_superuser', 'is_active', 'is_staff', 'password', 'last_login',]
        filtering = {
            'location': ('exact'),
        }

    def obj_create(self, bundle, **kwargs):
        bundle.obj = self._meta.object_class.objects.create_user(
            username=kwargs['username'],
            email=kwargs['email'],
            password=kwargs['password1'],
        )
        return bundle

Leave a comment