Django Tastypie用户注册

时间:2012-05-21 20:34:46

标签: python django api rest tastypie

我正在使用Django和TastyPie创建API。我试图通过资源注册用户。我从这个具有类似目标的问题中获取了大部分代码:

How to create or register User using django-tastypie API programmatically?

我的问题是,我在注册用户时遇到了问题。

代码是:

class RegisterUserResource(ModelResource):
    class Meta:
        allowed_methods = ['post']
        object_class = VouchersUser

        authentication = Authentication()
        authorization = Authorization()

        include_resource_uri = False
        fields = ['username']

        resource_name = 'register'

    def obj_create(self, bundle, request=None, **kwargs):
        try:
            bundle = super(RegisterUserResource).obj_create(bundle, request, **kwargs)
            bundle.obj.set_password(bundle.data.get('password'))
            bundle.obj.save()
        except IntegrityError:
            raise BadRequest('User with this username already exists')
        return bundle

当我使用用户名和密码参数发送POST(我以编程方式执行)时,我收到以下错误:

{"error_message": "The format indicated 'multipart/form-data' had no available deserialization method. Please check your formats and content_types on your Serializer.", "traceback": "Traceback (most recent call last):

 File "/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/resources.py", line 195, in wrapper
 response = callback(request, *args, **kwargs)

 File "/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/resources.py", line 402, in dispatch_list
 return self.dispatch('list', request, **kwargs)

 File "/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/resources.py", line 431, in dispatch
 response = method(request, **kwargs)

 File "/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/resources.py", line 1176, in post_list
 deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))

 File "/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/resources.py", line 351, in deserialize
 deserialized = self._meta.serializer.deserialize(data, format=request.META.get('CONTENT_TYPE', 'application/json'))

 File "/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/serializers.py", line 192, in deserialize
 raise UnsupportedFormat("The format indicated '%s' had no available deserialization method. Please check your formats and content_types on your Serializer." % format)

UnsupportedFormat: The format indicated 'multipart/form-data' had no available deserialization method. Please check your formats and content_types on your Serializer.
"}

我可以推断出序列化器存在一些问题但是我该如何解决呢?

谢谢

2 个答案:

答案 0 :(得分:2)

我猜你正在尝试将django.test.client.post与Tastypie一起使用。如果是这样,您需要传入一个额外的参数 - content_type。以下是您的通话方式:

client.post('/resource/to/create/', 'json_string_here', content_type='application/json')

答案 1 :(得分:1)

有同样的问题。在标题中传递“Content-Type:application / json”为我解决了这个问题。

相关问题