Django passes object from view to next for processing

If you have 2 views, the first uses a model form that accepts the entered information from the user (date of birth, name, phone number, etc.), and the second uses this information to create the table.

How would you pass the created object in the first view to the next view so that you can use it in the second view template

I would be grateful for any help you can provide.

+7
source share
2 answers

One approach is to put an object in a session in your first view, which can then be retrieved from request.session in the second view.

def first_view(request): my_thing = {'foo' : 'bar'} request.session['my_thing'] = my_thing return render(request, 'some_template.html') def second_view(request): my_thing = request.session.get('my_thing', None) return render(request, 'some_other_template.html', {'my_thing' : my_thing}) 
+9
source

Use HttpResponseRedirect to go to the table view with the newly created object identifier. Here is a shortened example:

 def first(request): if request.method == 'POST': form = MyModelForm(request.POST, request.FILES) if form.is_valid(): my_model = form.save() return HttpResponseRedirect('/second/%s/' % (my_model.pk)) # should actually use reverse here. # normal get stuff here def second(request, my_model_pk): my_model = MyModel.objects.get(pk=my_model_pk) # return your template w/my model in the context and render 
+2
source

All Articles