Nie Selam
Nie Selam

Reputation: 1451

Calling a class-based view of an app from another app in same project

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

Upvotes: 0

Views: 3914

Answers (2)

Vishal Dindalkop
Vishal Dindalkop

Reputation: 17

Make use of this import statement

from appName.views import viewName as variable_Name

Later Call it by

return variable_Name(request)

Upvotes: 1

Nie Selam
Nie Selam

Reputation: 1451

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

view = Browse.as_view()
return view(request)

Upvotes: 3

Related Questions