python – Django obj_create在我的表单验证之前运行
作者:互联网
在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'])
解决方法:
你正在做obj_create压倒错误. obj_create还应该处理数据验证.如果查看源代码here,您将看到调用self.save(bundle)方法.除其他外,该方法调用运行验证器的is_valid方法.在您的情况下,obj_create方法可能如下所示:
def obj_create(self, bundle, **kwargs):
bundle.obj = CompanyUser()
bundle = self.full_hydrate(bundle)
bundle.obj.password = bundle.data['company']
return self.save(bundle)
请注意,由于您的资源是ModelResource,full_hydrate将为您在bundle.obj上设置必要的属性.重要的是调用self.save(bundle)并返回它的结果.
如果你真的想使用CompanyUser.objects.create_user(),请试试这个:
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
标签:python,django,tastypie 来源: https://codeday.me/bug/20190831/1775643.html