Django Tastypie Custom Objects Only

I want to use Tastypie authorization to give users access only to their objects. However, I am having trouble understanding whether I am doing this correctly. I followed the example here:

http://django-tastypie.readthedocs.org/en/latest/authorization.html#implementing-your-own-authorization

When I try to create a new object, I get a 404 error because there are problems with the evaluation

def create_detail(self, object_list, bundle): return bundle.obj.user == bundle.request.user 

Everything works if I comment on this. I thought that commenting on these two lines would allow the user to create objects for other users, but when I tried, I got the 401 (UNAUTHORIZED) answer correctly.

Does this mean that these two lines are not needed? How can Tastypie correctly determine if I am allowed to create objects?

When I ran this, I sent a POST request with a "user" equal to the corresponding URI (something like "/ api / v1 / user / 1 /"). I'm not sure Tastypie is having trouble defining

 bundle.obj.user 

when i do it.

Can you just leave these two lines commented out? Is Tastypie user authorization one of the other methods?

+4
source share
2 answers

to try:

 def create_detail(self, object_list, bundle): return bundle.obj == bundle.request.user 
0
source

It seems that bundle.obj is not populated during authorization of create_detail.

In addition, create_detail for the user really does not make much sense, because there is no object for the user who will own until it is created in any case. You can simply check if bundle.request.user is a valid user with model permissions.

In my case, I needed to check if the created object was referencing an object belonging to the user, so here is what I came up with:

 def create_detail(self, object_list, bundle): resource=BookResource() book=resource.get_via_uri(bundle.data["book"], bundle.request) return book.user == bundle.request.user 

Anyway, bottom line: tastypie docs don't work a bit.

And hopefully this will help.

0
source

Source: https://habr.com/ru/post/1492189/


All Articles