1
感谢您阅读此问题。需要你的帮助。Django Tastypie v0.11.1,POST请求,无法使用obj_create保存数据
我正在学习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": "[email protected]", "first_name": "pri", "last_name": "pri", "username": "[email protected]", "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
我做错了什么。答案,非常感谢。谢谢 。 :)