Home > Software engineering >  View takes 1 positional argument but 2 were given
View takes 1 positional argument but 2 were given

Time:12-15

Trying to make a POST request to openAI with the input:

{"write hello world"}

but getting the error:

TypeError: View.__init__() takes 1 positional argument but 2 were given

Here is my view:

def get_help(user_input):
    response = openai.Completion.create(
        engine="text-davinci-002",
        prompt="user_input",
        temperature=0.5,
        max_tokens=1024,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0
    )
    return response["choices"][0]["text"]

@api_view(['POST'])
class receive_response(View):
    def post(self, request):
        user_input = request.POST["user_input"]
        response = get_help(user_input)
        return HttpResponse(response)

and my urls.py:

urlpatterns = [
    path("get", get_help, name="get_help"),
    path("post", receive_response, name="post"),
]

CodePudding user response:

Your problem is on this line: class receive_response(View):

(Why does receive_response inherit from view?)

Essentially what is happening is:

  • POST Request is received
  • request_received object is initialized (with the args of the POST - of which there must be two)
  • since it inherits from View (and no __init__() is specified, the parent class' __init__() is passed the same inputs
  • since View.__init__() accepts a single input value, but it received two, you get your error: TypeError: View.__init__() takes 1 positional argument but 2 were given

Add a def __init__(self, v1, v2): declaration to your class, and debug it to see what v1/v2 are (and decide which/what to pass to super().__init__() (View's constructor)

  • Related