Django Tastypie v0.11.1,POST请求,无法使用obj_create保存数据

时间:2014-02-21 05:34:08

标签: python django python-2.7 request tastypie

感谢您阅读此问题。需要你的帮助。

我正在学习Tastypie。所以尝试了以下任务。

我有以下型号。

帐户/ models.py

class UserProfile(models.Model):
    user            =   models.ForeignKey(User)
    user_type       =   models.CharField(max_length=12, blank=True, null=True)

    def __unicode__(self):
        return self.user.username

项目/ urls.py

from accounts.api import UserProfileResource, UserResource
from tastypie.api import Api

v1_api = Api(api_name='v1')
v1_api.register(UserResource())
v1_api.register(UserProfileResource())

urlpatterns += patterns('',
    (r'^api/', include(v1_api.urls)),
)

帐户/ api.py

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'

class UserProfileResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user')

    class Meta:
        queryset = UserProfile.objects.all()
        resource_name = 'userprofile'
        allowed_methods = ['get', 'post', 'put', 'delete', 'patch']
        always_return_data = True
        authorization= Authorization()
        authentication = Authentication()
        include_resource_uri = False

    def obj_create(self, bundle, **kwargs):
        try:
            bundle = super(UserProfileResource, self).obj_create(bundle, **kwargs)
            bundle.obj.user.set_password(bundle.data['user'].get('password'))
            bundle.obj.user.save() 
        except IntegrityError:
            print "error : user already exists."
            raise BadRequest('That username already exists')
        return bundle

当我重定向到http://127.0.0.1:8000/api/v1/userprofile/?format=json时。我可以在json fromat中看到存储在表格中的数据。

{
    "meta": {
        "limit": 20,
        "next": null,
        "offset": 0,
        "previous": null,
        "total_count": 9
    },
    "objects": [
        {
            "id": 1,
            "user": "/api/v1/user/1",
            "user_type": null
        },
        {
            "id": 2,
            "user": "/api/v1/user/2",
            "user_type": null
        },
    ]
}

所以GET按预期工作。

现在我正在尝试使用requests

使用以下脚本POST数据来存储数据
import requests
import json
headers = {'content-type': 'application/json'}
url = 'http://127.0.0.1:8000/api/v1/userprofile/?format=json'
data = {"user": {"email": "pri@dev.com", "first_name": "pri", "last_name": "pri", "username": "pri@dev.com", "password": "pri"}, 'user_type' : 'dev'}
response = requests.post(url, data=json.dumps(data), headers=headers)
print response.content

响应为空。在服务器中,我得到以下日志:

[21/Feb/2014 10:53:58] "POST /api/v1/userprofile/?format=json HTTP/1.1" 401 0

我做错了什么。答案,非常感谢。谢谢 。 :)

1 个答案:

答案 0 :(得分:1)

我自己找到了答案。所以,如果有人面临同样的问题,请在此处发布

我这样做了:

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        authorization= Authorization()

所以我理解的是在与外键连接的资源的META类中添加Authorization()