[Django]-Django obj_create runs before my form validation

5👍

You are doing the obj_create overriding wrong. obj_create should also handle data validation. If you look at the source code here, you’ll see that a self.save(bundle) method is called. That method, amongst other things, calls the is_valid method which runs the validator. In your case, the obj_create method could look like this:

def obj_create(self, bundle, **kwargs):
    bundle.obj = CompanyUser()
    bundle = self.full_hydrate(bundle)
    bundle.obj.password = bundle.data['company']
    return self.save(bundle)

Note that since your resource is ModelResource, full_hydrate will set up necessary attributes on the bundle.obj for you. The important thing is to call self.save(bundle) and return the result of it.

If you really want to use CompanyUser.objects.create_user() try this one instead:

def obj_create(self, bundle, request=None, **kwargs):
    bundle.obj = CompanyUser.objects.create_user(email=bundle.data['email'],
                                                 company=bundle.data['company'],
                                                 password=bundle.data['company'])
    self.is_valid(bundle)
    if bundle.errors:
        raise ImmediateHttpResponse(response=self.error_response(bundle.request, bundle.errors))
    return bundle

Leave a comment