Tastypie - No Attributes Found

I have this code:

#api model class VideoResource(ModelResource): class Meta: queryset = Video.objects.all() include_resource_uri = False resource_name = 'video' authorization = DjangoAuthorization() class QuestionResource(ModelResource): user = fields.ToOneField(UserResource,'user',full=True) video = fields.ForeignKey(VideoResource,'video',full=True) class Meta: queryset = Question.objects.all() resource_name = 'question' include_resource_uri = False authorization = DjangoAuthorization() def obj_create(self, bundle, request=None, **kwargs): import json temp = json.loads(request.body, object_hook=_decode_dict) video = Video.objects.get(pk=temp['video']) return super(QuestionResource, self).obj_create(bundle, request, user=request.user, video=video) #model class Question(models.Model): text = models.CharField('Question',max_length=120) created = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField(default=True) flag = models.BooleanField(default=False) allow_comments = models.BooleanField(default=True) thumbnail_url = models.CharField(default='video.jpg',blank=True, null=True,max_length=200) user = models.ForeignKey(User) video = models.ForeignKey(Video) def __unicode__(self): return self.text; class Video(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now_add=True) url = models.URLField(default="") user = models.ForeignKey(User) def __unicode__(self): return str(self.pk) + ' > ' + self.status 

The problem is that I get this error when sending this object:

 {"video":21,"text":"sadasds"} 

In the "video" field, data was provided that were not a URI, not a dictionary and does not have the attribute "pk": 21.

If I comment on this line:

 video = fields.ForeignKey(VideoResource,'video',full=True) 

Everything works fine, but then I can not get this information (video) when requesting /api/v1/questions/

My question is:

Perhaps your eyes can help me find a mistake :) Thank you!

+7
source share
1 answer

In the "video" field, data was provided that was not a URI, but not like a dictionary, and did not have the attribute "pk": 21.

So this means that the integer 21 does not meet the requirements for this field, it also gives an indefinite hint that it will meet the requirements.

firstly, you can send to the URI for writing, this is probably the most correct way, since the URIs are really unique, but pk is not.

 {"video":"/api/v1/video/21","text":"sadasds"} 

or you can send to a dictionary-like object with a set of pk fields.

 {"video":{'pk':21},"text":"sadasds"} 

The reason it works when you comment out the ForeignKey field is because tastypie then treats it as an IntegerField that can be referenced by a simple integer.

It helped me for a while, hoping it would help!

+6
source

All Articles