0

I have this class based view:

class Browse(APIView):
'''
Browse associations

'''
permission_classes = [TokenHasReadWriteScope]

def get(self,request,format=None):
    reply={}
    status=200


    try:
        filter_options={}
        name=request.query_params.get('name','').strip()
        if name:
            filter_options['name__icontains']=name


        associations=Association.objects.filter(**filter_options)values('id','name')
        page=request.query_params.get('page',1)
        paginator=Paginator(associations,20)
        data=paginator.page(page)
    except PageNotAnInteger:
        data=paginator.page(1)
    except EmptyPage:
        data=paginator.page(paginator.num_pages)

    except:
        status=400
        reply['detail']=(_('ErrorProcessingRequest'))

    if status==200:
        reply['associations']=list(data)
        reply['total_num_of_pages']=paginator.num_pages
        reply['total_rows_found']=paginator.count

    return JsonResponse(reply,status=status)

Now I have another app that is oriented towards internal users (different login and all) but I want to list the associations still. The above code is short and i don't mind pasting it there but just wondering if I can avoid DRY by calling the Browse from views.py of another app.

Currently, I trie this from app 2:

      from app1.views import Browse
      b=Browse()
      #but I cant serialize it as it returns <app1.views.Browse object at 0x0000000006CE0E80> is not JSON serializable
Rodriguez David
  • 541
  • 9
  • 25
Nie Selam
  • 1,343
  • 2
  • 24
  • 56

2 Answers2

3

Solved it following this SO Answer. All I had to do was:

view = Browse.as_view()
return view(request)
Nie Selam
  • 1,343
  • 2
  • 24
  • 56
1

Make use of this import statement

from appName.views import viewName as variable_Name

Later Call it by

return variable_Name(request)
RalfFriedl
  • 1,134
  • 3
  • 11
  • 12
  • you can also use import statement like from appName.views import viewName return viewName(request) but if you already have view with same name in the current app then its better to avoid this method and do as mentioned as earlier – Vishal Dindalkop Nov 15 '18 at 17:41