Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django, return a value to the HTML file from a view when using a form

My index.html file contains three forms, each connect to my views.py file and perform some function, everything is working fine but I am not understanding how to get a returned value back to my html page to display it.

index.html:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Index</title>
</head>
<body>
    
    <form action="{% url 'start_or_end_fast' %}" method="POST">
        {% csrf_token %} 
        <button type="submit" name='start_fast' value='start_fast'>Add Fast</button>
    </form>

    <form action="{% url 'start_or_end_fast' %}" method="POST">
        {% csrf_token %} 
        <button type="submit" name='end_fast' value='end_fast'>End Fast</button>
    </form>

    <form action="{% url 'start_or_end_fast' %}" method="POST">
        {% csrf_token %} 
        <button type="submit" name='duration' value='duration'>Fast Duration</button>
    </form>

<!-- DISPLAY FAST DURATION ON THE PAGE -->
{% if duration %}
      <p>Fasting for {{duration}} </p>
{% endif %}
    
</body>
</html>

The third form is a button, when I press it the duration prints in the terminal.
views.py code to do that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#If pressing Fast Duration button, show the duration difference between the current fast start_date_time and the current time 
  elif request.method == 'POST' and 'duration' in request.POST:

   time_difference()
   return render(request,'startandstoptimes/index.html')

  else:
   return render(request,'startandstoptimes/index.html')


def time_difference():

   #Get the current date and time 
   current_time = datetime.now().strftime(("%Y-%m-%d %H:%M:%S"))
   time_now = datetime.strptime(current_time, "%Y-%m-%d %H:%M:%S")

   #find the current fast that has not finished yet 
   #Get the date and time of that fast
   get_start_date_time = logTimes.objects.get(fast_finished = False)
   fast_started = get_start_date_time.start_date_time
   
   #caluclate the difference between the start of the fast and the time right now
   difference = time_now - fast_started
   duration = difference.total_seconds() 
   days    = divmod(duration, 86400)      # Get days (without [0]!)
   hours   = divmod(days[1], 3600)        # Use remainder of days to calc hours
   minutes = divmod(hours[1], 60)         # Use remainder of hours to calc minutes
   seconds = divmod(minutes[1], 1)
   
   difference_less_microseconds = str(difference).split(".")[0]
   print(difference_less_microseconds)

Output in the terminal:

1:15:20
[12/Jul/2022 23:14:48] "POST /startandstoptimes/ HTTP/1.1" 200 1139

I am wondering if I need to use HttpResponse instead of request?
I have been researching and experimenting but the examples I find are a bit more complicated than what I am trying to achieve, any advice is appreciated.

>Solution :

You have to use the context for the template rendering to pass variables to the template.

views.py

  # ... your code
  elif request.method == 'POST' and 'duration' in request.POST:
    duration = time_difference()
    return render(request,'startandstoptimes/index.html', {'duration': duration})

Your time_difference() function has to return the value you like to diplay in the template

def time_difference():
   # ... your code
   difference_less_microseconds = str(difference).split(".")[0]
   return difference_less_microseconds
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading