1

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

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
4

2 回答 2

1

我通过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

希望它也适合你。

于 2012-06-27T12:05:40.473 回答
1

您可以使用验证,而不是在 object_create 中进行验证FormValidation将根据模型表单验证您的输入。例如

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 = {}
        validation = FormValidation(form_class=AddUser)
于 2012-06-27T12:17:08.010 回答