0

Is it possible to pass an instance of a class defined in one view to another view in Django?

I tried using session and am able to pass attributes but not able to pass a method. Ideally, I'd like to pass the class instance to session directly but I get an error saying 'Object is not JSON Serializable'

More context, I have 2 views. One renders a page for each user. It also declares a class (MyClass) with a method get_response() that returns a response based on an input text.

def display_user(request, pk, slug):

    obj = MyClass(...)

    ...

    request.session['obj_name'] = obj.name

    request.session['obj_method'] = obj.method(input_text)  # <-- how to pass method to session

    return render(request, 'page.html', context = {...})

I have a view that I can make api calls to get the response from the method of the class defined above.

def obj_api(request, pk, slug):

    obj_name =  request.session['obj_name'] # this works
    
    if request.method == 'POST':
        input_data = json.loads(request.body.decode('utf-8'))
        
        response = obj.get_response(input_data) # <-- how to get method from session

        ## response = request.session['obj_method'](input_data)
    ... 
    return JsonResponse(response_data, status=200)

Any help would be appreciated.

Satya
  • 1
  • 2
  • What is `MyClass(...)`? Why can't you create a new instance in the `obj_api` view? – Lord Elrond Oct 17 '20 at 04:45
  • MyClass() is how am initializing the class. e.g. MyClass(name='obj.created_by.username'). I am able to create a new instance in obj_api, but am trying to avoid doing that for each api call I make. Each object when create also needs to be trained and i'd like to do that training once when the user page loads and not for each api call. Ideally, I would like to be able to create an instance of my class once in the display_user view and use that trained object in the obj_api view. Happy to provide more details if that'll help further clarify the question. – Satya Oct 17 '20 at 06:24

0 Answers0