0

I want to make a calculation using a FormView as input. The result should be displayed on the same page where the form is located.

This is what I have so far:

urls.py in the 'capsules'-app:

from django.urls import path
from . import views

app_name = 'capsules'

urlpatterns = [
    path('functions/', views.CapsulesFunctionsView.as_view(), name='functions'),
    path('uniformity/', views.CapsulesUniformityOfMassView.as_view(), name='uniformity'),
]

forms.py:

from django import forms

class CapsulesUniformityOfMass(forms.Form):
    mass_1_caps_empty = forms.FloatField(label='Mass of 1 empty capsules [g]')
    mass_20_caps_full = forms.FloatField(label='Mass of 20 full capsules [g]')
    mass_max1 = forms.FloatField(label='Mass of heaviest capsule [g]')
    mass_min1 = forms.FloatField(label='Mass of lightest capsule [g]')

models.py is empty, since I do not want to save the contents to the database

views.py:

from django.views.generic import TemplateView
from .forms import CapsulesUniformityOfMass
from django.views.generic.edit import FormView

# Create your views here.

#View for Capsules
class CapsulesFunctionsView(TemplateView):
    template_name = 'capsules/functions.html'
# Create your views here.

class CapsulesUniformityOfMassView(FormView):
    template_name = 'capsules/uniformity.html'
    form_class = CapsulesUniformityOfMass
    success_url = 'result'

    def form_valid(self, form):
        mass_1_caps_empty = form.cleaned_data['mass_1_caps_empty']
        mass_20_caps_full = form.cleaned_data['mass_20_caps_full']
        mass_max1 = form.cleaned_data['mass_max1']
        mass_min1 = form.cleaned_data['mass_min1']
        mean_content = mass_20_caps_full/20 - mass_1_caps_empty
        if mean_content <= 0.3:
            diff = 0.1
        else:
            diff = 0.15
        upper1 = mean_content*(1+diff)
        upper2 = mean_content*(1+2*diff)
        lower1 = mean_content*(1-diff)
        lower2 = mean_content*(1-2*diff)
        return super().form_valid(form)


class ResultView(TemplateView):
    template_name = 'capsules/result.html'

uniformity.html:

{% extends "base.html" %}
{% load django_bootstrap5 %}
{% block body_block %}
  <h1>Enter capsules data</h1>
  <form class="custom-form" method="post">
    {% csrf_token %}
    {% bootstrap_form form %}
    <input type="submit" class="btn btn-primary" value="check">
  </form>
  {% if form.is_valid %}
    <!-- Results should be displayed here! -->
  {% endif %}

{% endblock %}

I would like to display the upper1, upper2, lower1, lower2 on the same page (uniformity.html)

Thanks

Amun_Re
  • 136
  • 6
  • Similar question has been asked before and already has an answer https://stackoverflow.com/questions/6907388/updating-context-data-in-formview-form-valid-method – Moein Babapour Jan 25 '22 at 03:56
  • Possible duplicate of https://stackoverflow.com/questions/6907388/updating-context-data-in-formview-form-valid-method – FLAK-ZOSO Feb 02 '22 at 20:11

0 Answers0