如何在Django的同一页面上拆分帖子视图 [英] how to split post view on the same page in django

查看:54
本文介绍了如何在Django的同一页面上拆分帖子视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这个问题是否有意义,但对此我感到很困惑.我有一个帖子列表视图,它在此处呈现了一些帖子.

I have no idea if this question make much sense or not but i am so confused about it. I have a post list view and it is rendering some of the post here.

我的问题是如何分割页面的各个部分.

My question is how can I split the sections of the page.something like this.

做出这种看法的方法应该是什么.

what should be the approach of making this kind of view.

这是我的帖子view.py

this is my posts view.py

posts/view.py

posts/view.py

class PostListView(ListView):
    model = Post
    template_name = 'posts/home.html'
    context_object_name = 'posts'
    ordering = ['-date_posted']

    def get_queryset(self):
        if not self.request.user.is_authenticated:
            return Post.objects.all()[:10]
        else : 
            return super().get_queryset()

posts/models.py

posts/models.py

django.db导入模型中的

from django.db import models
from django.utils import timezone
from slugger import AutoSlugField
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.

def upload_location(instance, filename):
    return "%s/%s" %(instance.slug, filename)

class Category(models.Model):
    title = models.CharField(max_length= 60)
    slug = AutoSlugField(populate_from='title')
    parent = models.ForeignKey('self',blank=True, null=True ,related_name='children',on_delete=models.CASCADE)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    def __unicode__(self):
        return self.title

    def __str__(self):
        return self.title



class Post(models.Model):
    title = models.CharField(max_length=120)
    slug = AutoSlugField(populate_from='title')
    image = models.ImageField(
        upload_to=upload_location,
        null=True, 
        blank=True,
    )
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)


    def __str__(self):
        return self.title


    def get_absolute_url(self, slug=None):
        return reverse("posts-detail", kwargs={"slug": self.slug})

推荐答案

您已将帖子分配给类别.每个帖子只能分配到一个类别(因为您具有从 Post Category 的FK).并且您要显示所有类别和每个类别下的10条最新帖子.

You have posts assigned to categories. Each post could be assigned only to one category (since you have FK from Post to Category). And you want to display all categories and 10 latest posts under each one.

我看到了几种解决方法.最简单的方法是使用属性扩展 Category 模型,该模型包含queryset以便以您希望其在首页上使用的方式检索相关帖子.

I see several ways of how to solve that. The easiest one is to extend Category model with property, containing the queryset to retrieve related posts in the way you want them for front page.

class Post(models.Model):

    title = models.CharField(max_length=255)
    category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='posts')
    date_posted = models.DateTimeField(default=timezone.now)


class Category(models.Model):

    title = models.CharField(max_length=255)

    @property
    def posts_for_frontpage(self):
        return self.posts.order_by('-date_posted')[:10]


class FrontpageView(ListView):

    model = Category
    template_name = 'frontpage.html'
    context_object_name = 'categories'

    def get_queryset(self):
        # select some categories for frontpage
        # all by default
        return Category.objects.all()

然后在模板中

{% for category in categories %}
    <h1>{{ category.title }}</h1>
    <hr />
    {% for post in category.posts_for_frontpage %}
        <h4>{{ post.title }}</h4>
    {% endfor %}
    <br />
    <br />
{% endfor %}

您还可以使用 select_related 减少查询数量,并使用 annotate 获取所有相关帖子.

You could also play with select_related to reduce number of queries and with annotate to get all related posts.

这篇关于如何在Django的同一页面上拆分帖子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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