Home > Enterprise >  How can I called a view within another view django
How can I called a view within another view django

Time:12-13

Currently, I have a view that essentially closes a lead, meaning that it simply copies the information from one table (leads) to another (deals), now what I really would like to do is that after clicking close, the user is redirected to another page where the user can update some entries (sales forecast), I have a view that updates the lead, so I thought that I can do something like below:

@login_required
def close_lead(request):
    id = request.GET.get('project_id', '')
    keys = Leads.objects.select_related().get(project_id=id)
    form_dict = {'project_id': keys.project_id,
                 'agent': keys.agent,
                 'client': keys.point_of_contact,
                 'company': keys.company,
                 'service': keys.services,
                 'licenses': keys.expected_licenses,
                 'country_d': keys.country
                 }

    deal_form = NewDealForm(request.POST or None,initial=form_dict)

    if request.method == 'POST':
        if deal_form.is_valid():
            deal_form.save()
            obj = Leads.objects.get(project_id=id)
            obj.status = "Closed"
            obj.save(update_fields=['status'])
            ## Changing the Forecast Table Entry
            forecast = LeadEntry.objects.filter(lead_id=id)
            for i in forecast:
                m = i
                m.stage = "Deal"
                m.save(update_fields=['stage'])
            messages.success(request, 'You have successfully updated the status from open to Close')
            update_forecast(request,id)

        else:
            messages.error(request, 'Error updating your Form')


    return render(request,
                  "account/close_lead.html",
                  {'form': deal_form})


This view provides the formset that I want to update after closing the lead

@login_required
def update_forecast(request,lead_id):
    # Gets the lead queryset
    lead = get_object_or_404(Leads,pk=lead_id)
    #Create an inline formset using Leads the parent model and LeadEntry the child model
    FormSet = inlineformset_factory(Leads,LeadEntry,form=LeadUpdateForm,extra=0)
    if request.method == "POST":
        formset = FormSet(request.POST,instance=lead)
        if formset.is_valid():
            formset.save()
            return redirect('forecast_lead_update',lead_id=lead.project_id)

    else:
        formset = FormSet(instance=lead)

    context = {
                'formset':formset
               }
    return render(request,"account/leadentry_update.html",context)

As you can see I’m calling this function update_forecast(request,id) after validating the data in the form, and I would have expected to be somehow redirected to the HTML page specified on that function, however, after clicking submit, the form from the first view is validated but then nothing happens, so I'm the function doesn't render the HTML page

My question how can I leverage existing functions in my views?, obviously, I will imagine that following the DRY principles you can do that in Django, so what am I doing wrong ?, how can I call an existing function within another function in views?

CodePudding user response:

A view returns a response object. In your current code, you're calling a second view but not doing anything with its response. If you just wanted to display static content (not a form that might lead to an action that cares about the current URL) you could return the response object from the second view - return update_forecast(request, id).

But since your second view is displaying a form, you care about what the action for the view from the second form is. The typical Django idiom is to have forms submit to the current page's URL - that wouldn't work if you just call it and return its response object. You could customize the action in the second view, say adding an optional parameter to the view, but the usual idiom for form processing is to redirect to the view you want to show on success. Just as you do in the update_forecast view. Something like this:

messages.success(request, 'You have successfully updated the status from open to Close')
return redirect('update_forecast', lead_id=id)
  • Related