htmx 和 django 基于类的视图
Posted
技术标签:
【中文标题】htmx 和 django 基于类的视图【英文标题】:htmx and django Class Based Views 【发布时间】: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>
【问题讨论】:
【参考方案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)
【讨论】:
以上是关于htmx 和 django 基于类的视图的主要内容,如果未能解决你的问题,请参考以下文章