Django pass object from view to next for processing

点点圈 提交于 2019-12-03 13:24:24

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})

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!