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
- [Answered ]-Django 404 Page not loading
- [Answered ]-Static js doesn't load โ Django
- [Answered ]-Django ManyToManyField reverse Relationship
- [Answered ]-Django, unicode object has no attribute pk
- [Answered ]-Serve entirely static (documentation) website from Django url in Django 1.10
Source:stackexchange.com