[Answered ]-Obj_create not working in tastypie

1๐Ÿ‘

โœ…

I did the same by creating UserResource only.

class UserResource(ModelResource):
   class Meta:
       queryset = User.objects.all()
       resource_name = 'user'
       excludes = ['id','email', 'password', 'is_active', 'is_staff', 'is_superuser']
       list_allowed_methods = ['post']
       detail_allowed_methods = ['get']
       default_format = "application/json"
       filtering = {
           'username': ALL,
       }
       authorization= Authorization()

def obj_create(self, bundle, request = None, **kwargs):
    bundle.obj = self._meta.object_class()
    for key, value in kwargs.items():
        setattr(bundle.obj, key, value)
    bundle = self.full_hydrate(bundle)

    self.is_valid(bundle,request)

    if bundle.errors:
        self.error_response(bundle.errors, request)

    # Save FKs just in case.
    self.save_related(bundle)

    obj = None
    try:
        obj = self.obj_get(request, username=bundle.obj.username) # here it checks withe username is already exists or not
    except self._meta.object_class.DoesNotExist:
        pass

    # if user already found then just build the bundle else it will create the new user
    if obj:
        bundle = self.build_bundle(obj=obj, request=request)
    else:
        # Save parent
        bundle.obj.save()
        # Now pick up the M2M bits.
        m2m_bundle = self.hydrate_m2m(bundle)
        self.save_m2m(m2m_bundle)

    return bundle

Hope it works for you too.

๐Ÿ‘คAhsan

1๐Ÿ‘

Instead of validating in object_create, you could use validation. FormValidation would validate your entry against a model Form. e.g.

class UserResource(ModelResource):
    class Meta:
        object_class = User
        queryset = User.objects.all()
        resource_name = 'user'
        allowed_methods = ['get', 'post', 'delete', 'put']
        #excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
        filtering = {}
        validation = FormValidation(form_class=AddUser)
๐Ÿ‘คJamesO

Leave a comment