Django, возврат значения в HTML-файл из представления при использовании формы

Мой файл index.html содержит три формы, каждая из которых подключается к моему файлу views.py и выполняет некоторую функцию, все работает хорошо, но я не понимаю, как получить возвращаемое значение обратно на мою html-страницу, чтобы отобразить его.

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>

Третья форма - это кнопка, при нажатии на которую в терминале печатается длительность. Код views.py для этого:

#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)

Вывод в терминале:

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

Мне интересно, нужно ли мне использовать HttpResponse вместо request? Я исследовал и экспериментировал, но примеры, которые я нашел, немного сложнее, чем то, чего я пытаюсь достичь, любой совет будет оценен по достоинству.

Вы должны использовать контекст для рендеринга шаблона, чтобы передать переменные в шаблон.

views.py

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

Ваша функция time_difference() должна возвращать значение, которое вы хотите отобразить в шаблоне

def time_difference():
   # ... your code
   difference_less_microseconds = str(difference).split(".")[0]
   return difference_less_microseconds
Вернуться на верх