10

If you have 2 views, the first uses modelform that takes inputted information from the user (date of birth, name, phonenumber, etc), and the second uses this information to create a table.

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

I'd appreciate any help you can share

JohnnyCash
  • 1,231
  • 6
  • 17
  • 28

2 Answers2

14

One approach is to put the object into a session in your first view, which you could then retrieve from the 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})
Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
  • could you clarify what you mean by that? maybe a link to a relevant django document? I'm still learning this stuff Thanks for your reply though! – JohnnyCash Jan 26 '12 at 19:42
  • I added an example to my answer for you. – Brandon Taylor Jan 26 '12 at 19:44
  • this looks like it might work for me! One last question though, (bare with me i'm sorry).. how do i call on the saved form from the template? do I call them by what they're called in the template for the first view? Thanks again! – JohnnyCash Jan 26 '12 at 20:04
  • p.s, the my_object in your example = form.save() in my problem.. since I'm saving the inputted stuff.. – JohnnyCash Jan 26 '12 at 20:06
  • if it's a model form, it will return the object when .save() is called, like such: my_thing = form.save(). Then you can put my_thing into session, and pick it up in the second view. If it's not a model form, you could just make a dictionary of the values you need from form.cleaned_data and put that into session. – Brandon Taylor Jan 26 '12 at 20:08
  • 1
    What is the variable I want to pass is not JSON serializable, like for example, and instance? – Miguel Mar 05 '19 at 22:49
  • @Miguel you might look here for some ideas: https://stackoverflow.com/questions/757022/how-do-you-serialize-a-model-instance-in-django – Brandon Taylor Mar 06 '19 at 02:05
2

Use a HttpResponseRedirect to direct to the table view w/the newly created object's id. Here's an abbreviated 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
Sam Dolan
  • 31,966
  • 10
  • 88
  • 84