0

I have been assigned a project which has two versions of it: older one is written in django and new one written in django rest framework.

I am quite new to both django and drf. While going through both codebase, I came across following code in one of the views.py in new drf version:

def get_xyz(request):
    # some business logic
    return HttpResponse(json.dumps({ ... })
                        , content_type="application/json"
                        , status=status.HTTP_200_OK)

Then in older version of the app, I found function with exactly same above structure in its views.py. This created following confusions in me:

  1. Can we use function based views (as above) written in (non-drf) django app as it is in drf based app?

  2. Can we use class based views (as shown below) from non-drf django app as it is in the drf based app?

     class AbcClass(View):
         def get(self, request):
             # business logic
             return HttpResponse(json.dumps({ ... })
                                 , content_type="application/json"
                                 , status=status.HTTP_200_OK)
    
         def post(self, request):
             # business logic
             return HttpResponse("success", status.HTTP_200_OK)
    
  3. Does all django framework (non-rest) classes (like View above) work perfectly in drf?

  4. Can we make frontend app written in react (or angular) send requests and receive responses from old django app (similar to how frontend apps built with these UI frameworks are usually made to communicate with APIs built in drf)?

1 Answer 1

1

Yes, DRF extends the django framework by providing generics view and toolkit for them (routing, models, serializer, etc). But at the end, all it does is bind a function (the method of class based views) to a specific route/request. Django admin will still work without DRF, and any extra application that you already defined (and usually you bind those application to a api route using the url.py file).

For building an SPA with django, that's totally doable, as long as you return any type of data that your client can consume (usually application/json mime type). DRF is "only" a wrapper around django to do that (with a nice architecture, modular and decoupled features), but returning json in django is as simple as returning a JsonResponse object from your view function (https://docs.djangoproject.com/fr/4.1/ref/request-response/).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.