djangocalculator

Django BMI calculator not showing results


I'm trying to create a simple BMI calculator in django and for the life of me I cannot figure out why the app doesn't show the result after I press the calculate button. Does anyone have any insights on why this may be?

views.py

def calculate(response):
    if response.method == "POST":
        form = BMIform(response.POST)
        if form.is_valid():
            weight = form.cleaned_data["weight"]
            height = form.cleaned_data["height"]
            bmi = weight / height ** 2
            return render(request, "main/calculate.html", 
                          {"form": form, "bmi": bmi})
    else: 
        form = BMIform
    return render(response, "main/calculate.html", {"form": form})

models.py

class BMImodel(models.Model):
    weight = models.FloatField()
    height = models.FloatField()
    
    def bmi(self):
        return weight / height ** 2

forms.py

class BMIform(ModelForm):
    weight = forms.FloatField()
    height = forms.FloatField()
    class Meta:
        model = BMImodel
        fields = "__all__"

html file for the calculations

{% extends 'main/base.html' %}
{% block content %}
<h1><center>Calculate your BMI</center></h1>

<style>
    .btn-primary {
        background-color: rgb(82, 200, 216);
        color: black;
        border: none;
    }
    .btn-primary:hover {
        background-color: rgb(0, 128, 145);
        color: white);
    }
</style>
    {% csrf_token %}
    {{ form }}
    <div class="form-group col-md-4">
        <button type="submit" name="calculate" class="btn btn-primary">Calculate</button>
    </div>
    {% if bmi %}
        <div class="form-group col-md-4">
            <h5>BMI: {{bmi}}</h4>
        </div>
    {% endif %}
  </form>
{% endblock %}

I tried following several different tutorials but got lost somewhere along the way.


Solution

  • You're missing the opening tag of <form method="post">.

    Also, in the views, you're returning the bound form when it's valid, which will return all the data the user last entered. You need to instantiate a new form instead:

    if form.is_valid():
        ...
        form = BMIform()
        ...