Home > Enterprise >  How to show the saved data of 3 forms in my template in Django?
How to show the saved data of 3 forms in my template in Django?

Time:03-03

let's say I have a form_1 (PresupuestosClientesForm) and form_2 (PresupuestosVehiculosForm), those forms store information and they are in different html pages. I would like to have a view that presents the information saved in forms 1 and 2 in the same template. How can I do that?

With my view i am only retrieving the form but not the saved data of the form

view.py

def step7(request):

    presupuestosclientesform=PresupuestosClientesForm(request.POST or None,request.FILES or None)
    presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None,request.FILES or None)

    if request.method == 'POST':
        pass
    if presupuestosclientesform.is_valid():
        presupuestosclientesform.save()
        return redirect('presupuestos:index')
    return render(request,'Presupuestos/new-estimate-7-preview.html',{'presupuestosclientesform':presupuestosclientesform,'presupuestosvehiculosform':presupuestosvehiculosform})


index.html

<div >
    <p ><i ></i> 
       {{presupuestosclientesform}}
    </p> 
</div>
<div >
    <p ><i ></i> 
       {{presupuestosvehiculosform}}
    </p> 
</div>

CodePudding user response:

So to use Django forms for editing data, we first need to prepopulate those forms with the data that we want to edit then pass them as dictionaries to Django templates. You can do that in this way...

def step7(request):
    instance1 = get_object_or_404(ModelName, id=value) #Fetch data that you want to change from the model according to your needs.
    instance2 = get_object_or_404(ModelName, id=value) #Fetch data that you want to change from the model according to your needs.
    
    if request.method == 'POST':
       form1 = AddForm(request.POST)
       if form.is_valid():
          form.save()
          return HttpResponseRedirect('url_name')    
    
    else:
      first_form = AddForm(instance=instance1) #Here is the change
      second_form = AddForm(instance=instance2) #Here is the change
      return render(request, 'TemplateName', {'first_form ': first_form, 'second_form': second_form  })
  • Related