在Django中自定义标签以过滤Post模型中的帖子 [英] Customising tags in Django to filter posts in Post model

查看:107
本文介绍了在Django中自定义标签以过滤Post模型中的帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速提问-我不确定解决此问题的正确方法是什么.本质上,我希望定义一个处理一些逻辑的自定义标记,然后返回is_featured字段设置为True的模型Post的所有帖子.我尝试了多种方法来使此工作正常进行,但没有一个有效.我最后的连贯猜测"如下:

Quick question - I'm not sure what would be the correct way to handle this. Essentially I wish to define a custom tag which handles some logic then returns all posts of model Post which has the is_featured field set to True. I have tried a number of avenues to get this working, but none have worked. My last coherant "guess" was the following:

templatetags/blog_tags.py:

templatetags/blog_tags.py:

@register.inclusion_tag('blog/post/featured_posts.html')
def show_featured_posts(count=4):
    """Return 4 of the most recent posts (of model: 'Post') that has the variable is_featured set to True."""
    if Post.is_featured:
        featured_posts = Post.published.order_by('-publish')[:count]

return { 'featured_posts': featured_posts}

models.py(有用的位):

models.py (useful bits):

class PublishedManager(models.Manager):

    def get_queryset(self):
        return super(PublishedManager, self).get_queryset().filter(status='published')

class Post(models.Model):

    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )

    POST_TYPES = (
        ('news', 'News'),
        ('feature', 'Feature'),
        ('review', 'Review'),
    )

    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique_for_date='publish')

    author = models.ForeignKey(UserProfile, related_name='blog_posts')

    body = models.TextField()
    lead_in = models.CharField(max_length=500, default='')

    #These next items shall contain our development information for game reviews - this is much like the lead_in:
    platform = models.CharField(max_length=1000, default='')
    publisher = models.CharField(max_length=1000, default='')
    developer = models.CharField(max_length=1000, default='')
    release = models.DateTimeField(default=timezone.now)
    is_featured = models.BooleanField(default=False)

    #Out blog layout dictates each featurette has up to three scrolling images associated to it:
    image_scroll_1 = models.ImageField(storage=site_media_upload_location, null=True, blank=True)
    image_scroll_2 = models.ImageField(storage=site_media_upload_location, null=True, blank=True)
    image_scroll_3 = models.ImageField(storage=site_media_upload_location, null=True, blank=True)

    type = models.CharField(max_length=10,choices=POST_TYPES,default='review')

    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
    rating = models.PositiveSmallIntegerField(default=10)

    wrap_header = models.CharField(max_length=250, default='')
    wrap_up = models.TextField(default='')
    disclaimer = models.TextField(default='')

    objects = models.Manager()
    published = PublishedManager()
    tags = TaggableManager()

    class Meta:
        ordering = ('-publish',)

    def __str__(self):
        """Return the state title of the post"""
        return self.title

    def get_absolute_url(self):
        """Get absolute_url path specific to this post."""
        return reverse('blog:post_detail', args = [self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug])

    def get_image(self):
        """Get upload_to path specific to this photo."""
        return self.image.url

这就是我想包括的所有内容-我已经准备好使用featured_posts.html模板,因此我认为问题不在于此.它完全在blog_tags.py文件中.

That is everything I think I need to include - I have the featured_posts.html template all ready to go so I don't think the issue lies with that. It's purely in the blog_tags.py file.

推荐答案

将以下代码替换为blog_tags.py

replace the following code in blog_tags.py

 if Post.is_featured:
        featured_posts = Post.published.order_by('-publish')[:count]

featured_posts = Post.published.filter(is_featured=True).order_by('-publish')[:count]

这篇关于在Django中自定义标签以过滤Post模型中的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆