Using tastypie in sight

my first question is here:

So, I am using tastypie for api for my application.

I want to be able to use tastypie to render json and then include this in the django view so that I can load my application data.

Here is an example of this in the django tastypie cookbook: http://django-tastypie.readthedocs.org/en/latest/cookbook.html#using-your-resource-in-regular-views

The problem is that I CANNOT GET this for work, I tried the options from simpler to more complex, and I just can't get it, here is some code for my models:

class ChatMessage(models.Model): content = models.TextField() added = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(ChatUser, related_name="messages") chat_session = models.ForeignKey(ChatSession, related_name="messages") answer_to = models.ForeignKey('self', blank=True, null=True) flagged = models.BooleanField(blank=True,default=False) mododeleted = models.BooleanField(blank=True,default=False) mododeleted_by = models.ForeignKey(ChatUser,blank=True,null=True,default=None) mododeleted_at = models.DateTimeField(blank=True,null=True,default=None) [...] class ChatSession (models.Model): title = models.CharField(max_length=200) link_title = models.CharField(max_length=200) description = tinymce_models.HTMLField() date = models.DateTimeField() online = models.BooleanField(default=False) next_session = models.BooleanField(default=False) meps = models.ManyToManyField(ChatMep) uid_newsupdate = models.CharField(max_length=200,blank=True,null=True,default="") [...] 

and my resources:

 class ChatMessageResource(MyModelResource): chat_session = fields.ForeignKey(ChatSessionResource, 'chat_session') def renderOne(self,request,pkval): data = self.obj_get(None,pk=pkval) dbundle = self.build_bundle(obj=data,request=request) return self.serialize(None,self.full_dehydrate(dbundle),'application/json') def dehydrate(self, bundle): bundle.data['likes'] = bundle.obj.get_likes() bundle.data['likes_count'] = len(bundle.data['likes']) return bundle class Meta: authentication = Authentication() authorization = Authorization() queryset = ChatMessage.objects.all() resource_name = 'message' fields = ('content', 'added', 'flagged', 'mododeleted','author','answer_to','chat_session') filtering = { 'chat_session': ALL_WITH_RELATIONS, } 

and my view index:

 def index(request): cur_sess = get_current_chat_session() data1= ChatMessageResource().renderOne(request,723) return render_to_response('test.html', { 'all_data' : data1 }, context_instance=RequestContext(request)) 

What I want is my renderOne () function to give me json ONE ChatMessageResource In addition, I would like the renderAll () function to pass me ALL (or filter out) ChatMessageResources in json.

And I want to use the tastypie internals, I KNOW that I could serialize it myself, but that is not the point.

Now the error is:

 NoReverseMatch at /live/ Reverse for 'api_dispatch_detail' with arguments '()' and keyword arguments '{'pk': 14L, 'resource_name': 'session'}' not found. 

I'm just losing my mind, I tried for hours.

So, please, how to get ONE / ALL resource as JSON using code using tastypie in django view!

If this is not clear or I need to clarify, please just ask, thanks

Indeed, I want to get the JSON returned by the API URL that I created, but from the code, and not by visiting the URL .. So if I have /api/v1/messages/?chat_session=14 , which return a list of messages, I want to be able to do the same thing by code (and not by choosing a URL with a curl or something, please).

Note: definition of ModelResource.obj_get from https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py

 def obj_get(self, request=None, **kwargs): """ A ORM-specific implementation of ``obj_get``. Takes optional ``kwargs``, which are used to narrow the query to find the instance. """ try: base_object_list = self.get_object_list(request).filter(**kwargs) object_list = self.apply_authorization_limits(request, base_object_list) stringified_kwargs = ', '.join(["%s=%s" % (k, v) for k, v in kwargs.items()]) if len(object_list) <= 0: raise self._meta.object_class.DoesNotExist("Couldn't find an instance of '%s' which matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs)) elif len(object_list) > 1: raise MultipleObjectsReturned("More than '%s' matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs)) return object_list[0] except ValueError: raise NotFound("Invalid resource lookup data provided (mismatched type).") 
+6
source share
3 answers

So, I found a solution, the problem was resolving the URL ... I needed to add

 def get_resource_uri(self, bundle_or_obj): return '/api/v1/%s/%s/' % (self._meta.resource_name,bundle_or_obj.obj.id) 

for the linked object (session here) to make it work (don't ask why!)

So here is my working solution for renderDetail and renderList:

 def renderDetail(self,pkval): request = HttpRequest() request.GET = {'format': 'json'} resp = self.get_detail(request, pk=pkval) return resp.content def renderList(self,options={}): request = HttpRequest() request.GET = {'format': 'json'} if len(options) > 0: request.GET.update(options) resp = self.get_list(request) return resp.content 

And here is a usage example:

 cmr = ChatMessageResource() dataOne= cmr.renderDetail("723") dataAll = cmr.renderList({'limit':'0','chat_session':cur_sess.pk}) 
+9
source

https://github.com/toastdriven/django-tastypie/issues/962

I found that the obj_get method requires a related request object. See Link.

 def user_detail(request, username): ur = UserResource() # Add this request bundle to the obj_get() method as shown. req_bundle = ur.build_bundle(request=request) user = ur.obj_get(req_bundle, username=username) .... 
+2
source

Your problem seems to be here:

 data = self.obj_get(None,pk=pkval) 

obj_get parameters must be kwargs, which can be passed directly to standard get . None should not be there.

0
source

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


All Articles