【问题标题】:htmx and django Class Based Viewshtmx 和 django 基于类的视图
【发布时间】:2022-01-07 15:16:57
【问题描述】:

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

views.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>

【问题讨论】:

    标签: django htmx


    【解决方案1】:

    感谢@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)
    

    【讨论】:

      猜你喜欢
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      • 2015-08-25
      • 1970-01-01
      • 2011-01-23
      • 2014-02-16
      • 2011-10-04
      相关资源
      最近更新 更多