How to passing a value from one Django view to another view?

I have a value - obtained after saving a Django form. After saving the form - I redirect the Django application to another view. Along with redirecting to another view, I want to pass the value that was in the previous view.

How can this be done - passing a value from one Django view to another view?

I'm trying to do this one by one, but I'm getting an error.

If you have the opportunity, I would be grateful for any information or help.

view_1

def form_1(request):
    context = {}
    form_2 = Form_new_form1_1(request.POST or None)
    if form_2.is_valid():
        model_instance = form_2.save(commit=False)
        values_name = model_instance.name

        nm_kot = values_name
        request.session['nm_kot'] = nm_kot
        
        return redirect("form_1_2")
    
context['form_2'] = form_2
    return render(request, "form_1.html", context)

view_2

def form_1_2(request):
    context = {}
    nm_kot = request.session['nm_kot']
    nomer = nm_kot
    name = nomer
    
    return redirect("tabl_1")

error

 response = self.process_response(request, response)
 raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Model_Model is not JSON serializable
[05/Feb/2023 18:00:20] "POST /zamer_form_1 HTTP/1.1" 500 114735

Django session uses by defaut json serialization and therefore you will need to serialize your data to json.

I don't recommend switching to pickle which will solve your issue but is not recommended.

You can use json.dumps and json.loads to serialize and deserialize the data.

https://docs.djangoproject.com/en/4.1/topics/http/sessions/#session-serialization

https://docs.djangoproject.com/en/4.1/topics/http/sessions/#examples

Back to Top