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

标签 python django python-2.7 request tastypie

感谢您阅读这个问题。需要您的帮助。

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

我有以下型号。

accounts/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

project/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)),
)

accounts/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 正在按预期工作。

现在我尝试使用请求通过以下脚本发布数据来存储数据:

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

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

最佳答案

我自己找到了答案。因此,如果有人遇到同样的问题,请在这里发帖

我这样做了:

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

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

关于python - Django Tastypie v0.11.1,POST请求,无法使用obj_create保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21926089/

相关文章:

python - 使用 pyodbc 读取 SSMS 输出消息

python - 详细 View 和过期项目在 Django 中不起作用

Django Haystack 适合这种类型的搜索吗?

python-2.7 - 在进程之间共享字典

windows - 语法错误使用 Windows 替换 ("\\"、 "\") 来替换 Python 中的文件路径

python - 清理输入以在正则表达式中包含空格?

Python 属性错误 : 'module' object has no attribute 'get'

python - 解析 Python 文件以检索变量、值、函数定义

python - 计算两个值并计算Django中的百分比差异

python - 在 Uncaught Error 上启动 IPython session