简体   繁体   中英

Django Tastypie v0.11.1 ,POST request , Unable to save data with obj_create

Thanks for reading this question . Need your help.

I am learning Tastypie . So tried out following task.

I have following model.

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

when I redirect to http://127.0.0.1:8000/api/v1/userprofile/?format=json . I can see data stored in table in 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
        },
    ]
}

So GET is working as expected.

Now I am trying to POST data to store data with following script using requests :

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

Response is Empty . and in server , I get following log :

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

What I am doing wrong . Answers , Much appreciated . Thank you . :)

I found Answer myself. So posting here if anybody face same problem

I did this :

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

So what I understand is to add Authorization() in META class of Resource that is connected with Foreign key .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM