-1

I've got a Django rest framework APIView:

class MyAPIView(views.APIView):
    def post(self, request):
        field = request.POST.get("field")
        print(field)
        return Response({"field": field}, status=200)

I want to call it from separate process using Django API. I do it like this:

from django.http import HttpRequest, QueryDict

request = HttpRequest()
request.method = "POST"
request.POST = QueryDict(mutable=True)
request.POST["field"] = "5"
response = MyAPIView.as_view()(request=request)

But when field is being printed in MyAPIView it's always None. How to call post method using Django?

StuffHappens
  • 6,457
  • 13
  • 70
  • 95

1 Answers1

2
  1. If you need to call on view from another view - check this answers

  2. If you need to send request to the view

pip install requests or poetry add requests

from rest_framework.reverse import reverse
import requests as client

DOMAIN = "http://127.0.0.1:8080"

# your endpoint name (path name in urls.py)
# you can get name using django extenstions command `show_urls` if you dont know the path name
endpoint = reverse("my-api-view")

client.post(f"{DOMAIN}{endpoint}", data={"field": "5"})

django extensions

command show_urls

usage: python manage.py show_urls

  1. If you need exactly run the code of some view, why you cannot move this code to some function/static-method and call it in view and in other part of code?
  • In case of 3 some usefull information such as user, permissions, ect is missing. I know there's a way to make requests using requests package, but I'm interested in making it using Django or Django rest framework. – StuffHappens Dec 15 '22 at 15:21
  • u dont need to send request to view from the same django project. only in api tests. – Ruslan Korneev Dec 15 '22 at 15:26
  • in tests you need to use APIClient and reverse to send request and test you apiview – Ruslan Korneev Dec 15 '22 at 15:27