Doing math with django forms and avoiding redirect

Viewed 202

I would like to have a form in Django do some math and spit out a result that does not end up with a redirect and gives me the result on the same page (i.e without refreshing).

For example:

views.py:

def collisionrisk(request):
    assert isinstance(request, HttpRequest)

    form_class = CRMForm
    result = ''
    if request.method == 'POST':
        form = form_class(data=request.POST)

        if form.is_valid():
            D = form.cleaned_data['D']
            B = form.cleaned_data['B']
            b = form.cleaned_data['b']

            result = D*B+b
            return HttpResponse('')
    else:

        return render(
            request,
            'Collision_risk.html',
            {
                'form':form_class,
                'result':result
            }
        )

forms.py:

class CRMForm(forms.Form):
    D = forms.DecimalField(required=True)
    B = forms.IntegerField(required=True)
    b = forms.IntegerField(required=True)

    def __init__(self, *args, **kwargs):
        super(CRMForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)

        self.fields['b'].label = 'b'

        self.helper.layout = Layout(
            Div(
                Div('D',css_class='col-lg-offset-2 col-md-offset-2 col-lg-1 col-md-1 col-sm-12 col-xs-12'),
                Div('B',css_class='col-lg-1 col-md-1 col-sm-12 col-xs-12'),
                Div('b',css_class='col-lg-1 col-md-1 col-sm-12 col-xs-12'),
                css_class='row',
                css_style='padding-left:50px;padding-right:50px;'
            )
        )
        self.helper.add_input(Submit('submit', 'Submit', css_class='btn-primary outline',action="."))
        self.helper.form_method = 'POST'

Basically, in my template, I would like the user to hit "submit" and then the result of the math appear in a designated div on the same page (i.e. directly under the button without redirecting to a new page) .

I can do this in Jquery easy enough, but I am interested in learning if there is a pure Django way to do this first.

Thanks, folks!

1 Answers

Replace the statement from if statement

          return render(
            request,
            'Collision_risk.html',
            {
                'form': form_class,
                'result': result
            }
        )

by

from rest_framework.response import Response
return Response(request, 'Collision_risk.html', {'result':result})
Related