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

155 views Asked by At

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.

0

There are 0 answers