Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django pass object from view to next for processing

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

like image 577
JohnnyCash Avatar asked Jan 26 '12 19:01

JohnnyCash


2 Answers

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})
like image 140
Brandon Avatar answered Sep 20 '22 23:09

Brandon


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
like image 22
Sam Dolan Avatar answered Sep 18 '22 23:09

Sam Dolan