MattBroach / DjangoRestMultipleModels

View (and mixin) for serializing multiple models or querysets in Django Rest Framework
MIT License
549 stars 67 forks source link

Template do not return results data #6

Closed apishops closed 8 years ago

apishops commented 8 years ago

In case with TemplateHTMLRenderer temlate do not have results array for use.

class MyList(MultipleModelAPIView): flat = True filter_backends = [filters.OrderingFilter] serializer_class = MyListSerializer renderer_classes = [JSONRenderer, TemplateHTMLRenderer, BrowsableAPIRenderer] template_name = 'accounts/my/index.html' add_model_type = False

def get_queryList(self):
    queryList = [
        ( Record.objects.filter(author = self.request.user), MyListSerializer, 'community')
    ]
    return queryList
apishops commented 8 years ago

In case with native generic DRF view, results data is set

class MyList(generics.ListAPIView): filter_backends = [filters.OrderingFilter] queryset = Record.objects.all() serializer_class = MyListSerializer renderer_classes = [JSONRenderer, TemplateHTMLRenderer, BrowsableAPIRenderer] template_name = 'accounts/my/index.html' add_model_type = False

MattBroach commented 8 years ago

So, I found the problem: the MultipleModelAPIView always creates a list, but the TemplateHTMLRenderer needs a dictionary to properly make template context. So, I added a wrapper that checks to see if the requested format is html, and it will wrap that whole thing in the dictionary {'data': results} -- this means that your data will be available in the template now as:

{{ data }}

and, of course, you can get whatever you need from it, such as:

{{ data.0.recordAttribute }}

The new version is now up on PyPi, so grab it and let me know if there are any issues.