python - Django obj_create 在我的表单验证之前运行

标签 python django tastypie

在 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)

请注意,由于您的资源是 ModelResourcefull_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 obj_create 在我的表单验证之前运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19453625/

相关文章:

Python 使用 IPv6 地址解析主机名

django - 如何使用 TastyPie PATCH 更新密码

javascript - 启用 Django 和 Tastypie 对尾部斜线的支持?

python - 如何查找模型是否是从 Django Admin 或其他地方保存的

csrf - 如何关闭 tastypie 帖子中的 csrf?

python - 如何在 python 中解析带有 '+' 的标签

python - 更有效的数据结构/算法在数据库中查找相似的图像哈希

使用 vs2013 对类进行 Python RSA 解密

django - Haystack 和 Elasticsearch : Limit number of results

django - 如何在handlebars-django模板中引用静态文件