3

在 TastyPie obj_create 在我的表单验证之前运行,它似乎被跳过了,为什么?

我的代码

class AccountCreateResource(ModelResource):
    class Meta:
        queryset = CompanyUser.objects.all()
        resource_name = 'accounts/create'
        allowed_methods = ['post']
        validation = FormValidation(form_class=UserCreationForm)

    def obj_create(self, bundle, request=None, **kwargs):

        CompanyUser.objects.create_user(email=bundle.data['email'],
                                            company=bundle.data['company'],
                                            password=bundle.data['company'])
4

1 回答 1

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
于 2013-10-19T19:51:41.157 回答