1

Admin integration for django reversion is pretty straightforward. When I visit 127.0.0.1/admin I have the option for staff users to recover deleted objects or view previous versions.

But this is only from the admin side. How can I provide a public view for history objects? I'm attempting to provide history access via Django-REST-Framework.

Praneeth
  • 902
  • 2
  • 11
  • 25
  • what are you using for REST API? tastypie? DRF? other? – Ankit Popli Feb 23 '15 at 17:12
  • I'm using it for REST API. previously I have implemented django-reversion for admin integration @ http://stackoverflow.com/questions/28593989/how-to-add-django-reversion-to-an-app-developed-using-django-and-django-rest-fra for your cross reference – Praneeth Feb 23 '15 at 18:17

1 Answers1

4

Tastypie Approach

  • Create a resource for Version (from reversion.models import Version) with resource_name as 'versions'
  • Add the following url pattern to prepend_urls to the resources for which you have enabled reversion:

    url(r'^(?P<resource_name>{})/(?P<pk>\d+)/history{1}$'.format(self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_history'), name='history')
    
  • Paste the following code into the resource:

    def dispatch_history(self, request, **kwargs):
        try:
            bundle = self.build_bundle(data={
                'pk': kwargs['pk']
            }, request=request)
            obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
    
        _versions = reversion.get_for_object(obj)
        versions = []
        for version in _versions:
            _resource = api.canonical_resource_for('versions')
            _bundle = _resource.build_bundle(version)
            _bundle = _resource.full_dehydrate(_bundle)
            versions.append(_bundle)
        return self.create_response(request, versions)
    

Disclaimer: This code hasn't been tested, if it works in one go, then praise the lord.

PS: I'll be implementing a similar thing with DRF soon. Will update the answer when done.

Django Rest Framework

class VersionableModelViewSetMixin(viewsets.ModelViewSet):
    @detail_route()
    def history(self, request, pk=None):
        _object = self.get_object()
        _versions = reversion.get_for_object(_object)

        _context = {
            'request': request
        }

        _version_serializer = VersionSerializer(_versions, many=True, context=_context)
        # TODO
        # check pagination
        return Response(_version_serializer.data)

Include this Mixin in all the views containing models that have been registered with django-reversion.

Hope this helps a bit.

Best!!

Ankit Popli
  • 2,809
  • 3
  • 37
  • 61