python - obj_create 无法在 tastypie 中工作

标签 python django rest tastypie

我正在尝试使用 tastypie 实现用户注册,一切正常,但是当我尝试使用 obj_create 方法检查用户是否已经存在时,什么也没有发生... 如何在tastypie中调用它,它是自动调用的吗?

from _mysql_exceptions import IntegrityError
from django.db.models.query_utils import Q
from tastypie.authorization import Authorization
from django.contrib.auth.models import User
from tastypie.authentication import BasicAuthentication
from tastypie import fields
from tastypie.exceptions import BadRequest
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from tastypie.validation import Validation
from apps.eUser.models import  UserProfile

class ProfileResource(ModelResource):
    username = fields.CharField(attribute='user__username', readonly=True)
    id = fields.CharField(attribute='id')
    class Meta:
             queryset =UserProfile.objects.select_related('User')
             resource_name = 'profile'
             fields = ['id']

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 = {
        }

class CreateUserResource(ModelResource):
    class Meta:
        allowed_methods = ['post']
        object_class = User
        #authentication = Authentication()
        authorization = Authorization()
        resource_name = 'register'

        include_resource_uri = False
        fields = ['username','password','email']

    def obj_create(self, bundle, request=None, **kwargs):
     try:
        bundle = super(CreateUserResource, self).obj_create(bundle, request, **kwargs)
    except IntegrityError:
        raise BadRequest('That username already exists')
    return bundle

最佳答案

我通过仅创建 UserResource 做了同样的事情。

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

希望它也适合您。

关于python - obj_create 无法在 tastypie 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11225110/

相关文章:

python - Kivy Garden - 多个 Chromium 嵌入式浏览器,只能更改第一个创建的浏览器的 URL?

python - find_element_by_class_name 类空间不起作用

python - 如何编写 Django 查询,其中 WHERE 条件的左侧是数学表达式?

Python/Django TangoWithDjango 模型和数据库

python - 识别 bool 数组/blob 的内部 - NumPy/Python

python - 如何使用 python 将代理设置/凭据传递到命令提示符,以便同一 python 代码中的后续命令可以访问互联网?

python - scrapy可以从python中具有多个类的标签中找到类

python - Django : Project consuming data from REST API, 如何在本系统中使用外部应用程序?

php - 使用 php-github-api 的 Github 身份验证

c# - ASP.NET Web API 下载文本