I am building a homepage that has a dynamically updated blogs section and a BMI calculator section. Initially, the page loads perfectly fine. But the problem is that when I calculate the BMI (POST request) the page refreshes and the blogs section (GET) disappears.
my urls.py
urlpatterns = [
path('', HomeViews.as_view(), name='home_page'),
]
my views.py
class HomeViews(ListView, View):
template_name="home_page.html"
def get(self, request, *args, **kwargs):
posts_diet = BlogModel.objects.filter(cat__title='Healthy Diet').order_by('-created_at')[:1]
return render(request, 'home_page.html', {
'posts_diet' : posts_diet,
})
def post(self, request, *args, **kwargs):
if request.method == "POST":
# get input
height_metric = request.POST.get("height-metric")
weight_metric = request.POST.get("weight-metric")
#----bmi Formula-----
if height_metric:
bmi = float(weight_metric) / (float(height_metric)**2)
else:
bmi = 0
return render(request, 'home_page.html', {
'bmi': bmi,
})
my home_page.html
<div>
{% for pst in posts_diet %}
<div>
<img src="uploads/{{ pst.blog_main_image }}" />
<div>
<p>{{ pst.cat | striptags | slice:':50' }}</p>
<p>{{ pst.created_at | date:"M d, Y" |striptags | safe }}</p>
</div>
<div>
<h1>{{ pst.title | striptags | slice:':150' }}</h1>
<button></button>
</div>
</div>
</div>
{% endfor %}
my terminal:
# initial homepage request (everything loads perfectly fine)
[24/Dec/2021 14:34:21] "GET /static/css/dist/styles.css HTTP/1.1" 200 30992
[24/Dec/2021 14:34:21,606] - Broken pipe from ('127.0.0.1', 65275)
# on submitting POST request GET gets executed but GET content is not displayed
[24/Dec/2021 14:34:42] "GET / HTTP/1.1" 200 44233
[24/Dec/2021 14:34:42] "GET /static/css/dist/styles.css HTTP/1.1" 200 30992
[24/Dec/2021 14:35:41] "POST / HTTP/1.1" 200 37434
I think I can get away with this issue by using AJAX for form submission but that might not be a robust solution. Kindly advise …