0

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

如何以编程方式使用 django-tastypie API 创建或注册用户?

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

代码是:

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.
"}

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

谢谢

4

2 回答 2

2

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

client.post('/resource/to/create/', 'json_string_here', content_type='application/json')
于 2012-05-24T15:32:59.067 回答
1

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

于 2014-06-25T19:14:35.140 回答