【问题标题】:How to schedule posts for carousel in templates using django?如何使用 django 在模板中安排轮播的帖子?
【发布时间】:2022-01-26 07:45:37
【问题描述】:

我很难想出一个解决方案来解决如何在 django 中使用动态数据为引导轮播安排帖子。

例子:

如果今天是 2 月 1 日,我在 1 月 1 日至 1 月 30 日创建了一个帖子,该帖子不应该在轮播中可见,反之亦然。

Models.py

class Carousel(models.Model):

above_text = models.CharField(max_length=200, null=True)
below_text = models.CharField(max_length=200, null=True)
image = models.ImageField(upload_to='static/website/images/profile-images', null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
date_start = models.DateTimeField(null=True)
date_end = models.DateTimeField(null=True)

class Meta: 
    verbose_name_plural = 'Carousel'

def __str__(self):
    return f'{self.above_text} Carousel'

Views.py

def index(request):

car = Carousel.objects.all()
faq = FAQ.objects.all()
team = Team.objects.all()
about = About.objects.all()

context = {

    'car' : car,
    'faq' : faq,
    'team': team,
    'about' : about,


}

template_name = 'main/index.html'
return render(request, template_name, context)

模板

              <div class="carousel-inner">
                {% for car in car %}
                <div class="carousel-item {% if forloop.counter0 == 0%} active {% endif %}" data-interval="2">
                    <div class="img-caro">
                        <img src="{{car.image}}" class="img-responsive">
                    </div>
                    <div class="container">
                        <h1>{{car.above_text}}</h1>
                        <p>{{car.below_text}}</p>
                    </div>
                </div>
                {% endfor %}
            </div>
            

【问题讨论】:

  • 你能提供一些代码吗?
  • 我已经在我的编辑中发布了代码,感谢您的时间。

标签: javascript html css django django-models


【解决方案1】:

看起来您想在轮播对象在 date_start 和 date_end 之间处于活动状态时显示它们。好吧,你需要过滤你的对象。您可以在视图中过滤它们或为您的模型创建管理器。

在你的views.py:

car = Carousel.objects.all().filter(date_start__lte=datetime.now(), date_end__gte=datetime.now())

或使用经理:

class CarouselManager(models.Manager):

    def get_active(self):
        return super(CarouselManager, self).all().filter(date_start__lte=datetime.now(), date_end__gte=datetime.now())

【讨论】:

  • 感谢您的帮助,它成功了
猜你喜欢
  • 2021-02-23
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-18
  • 2012-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多