0

我试图将倒计时教程从这里转换为基于类的视图,但我不知道缺少什么。

视图.py

class TimeDifferenceView(TemplateView):
    
    delta = datetime(2022, 12, 1, tzinfo=timezone.utc) - timezone.now()
    template_name = 'base.html'
    days = delta.days
    seconds = delta.seconds % 60
    minutes = (delta.seconds //60) % 60
    hours = delta.seconds // 3600
    
    def get_context_data(self,*args, **kwargs):
        # Call the base implementation first to get the context
        context = super(TimeDifferenceView, self).get_context_data(*args, **kwargs)
        # Create any data and add it to the context.
        context['days'] = self.days
        context['seconds'] = self.seconds
        context['minutes'] = self.minutes
        context['hours'] = self.hours
        return context

base.html

<div
id= "time" 
class="d-flex justify-content-between"
hx-get="{% url 'time_difference' %}"
hx-trigger="every 1s"
hx-select="#time" 
hx-swap="outerHTML"
>    
            <div>
              <h5>Days</h5>
              <p> {{days}} </p>
            </div>
       
            <div>
              <h5>Hours</h5>
              <p> {{hours}} </p>
            </div>
          
            <div>
              <h5>Minutes</h5>
              <p> {{minutes}} </p>
            </div>
        
            <div>
              <h5>Seconds</h5>
              <p> {{seconds}} </p>
            </div>
</div>
4

1 回答 1

0

感谢@chuysc_ 这是工作代码。

from datetime import datetime
from django.views.generic.base import View
from django.utils import timezone
from django.shortcuts import render


class TimeDifferenceView(View):
    
    template_name = 'base.html'
    
    def get(self, request):
        
        delta = datetime(2022, 12, 1, tzinfo=timezone.utc) - timezone.now()

        context = {
            'days': delta.days,
            'seconds': delta.seconds % 60,
            'minutes': (delta.seconds //60) % 60,
            'hours': delta.seconds // 3600
        }
        return render(request, self.template_name, context)
于 2021-12-01T03:02:04.877 回答