[Answer]-Django Tastypie posting with ForeignKey

1đź‘Ť

âś…

You made SearchResource to have comments (m2m relation) but you didn’t specify it in model class Search, so I suppose you used reverse relationship.

If so, instead of,

class SearchResource(ModelResource):
    comments = fields.ToManyField('myapp.api.CommentResource','comments', null=True, blank=True)

change to,

class SearchResource(ModelResource):
    comments = fields.ToManyField('myapp.api.CommentResource', 'comment_set', related_name='search', null=True, full=True)

The problem “comment has no search” because you didn’t specify related_name. In another side, class Search has no attribute comments but comment_set (reverse relationship).

👤adityasdarma1

0đź‘Ť

It looks like you have a web page with a form that you’re attempting to send to tastypie. However, your data is generated by:

$("#commentForm").serialize()

That will generate URL encoded data, but you need to send JSON.

You’ll need to send the data as JSON. This might work instead:

JSON.stringify($("#commentForm").serializeArray());

This might not work directly. You might need to modify the result of serializeArray() into the proper format for tastypie before passing it into JSON.stringify().

👤dragonx

Leave a comment