簡體   English   中英

如何在 Django 中獲取來自 Category 的 Post 數據?

[英]How can get Post data form Category in Django?

我嘗試使用 Django 一點。 現在我堅持在該類別中發布問題。 我想知道我們如何使用它。 有什么我應該使用的過濾器嗎?

我的 model.py 中的代碼

   class Category(models.Model):
    title = models.CharField(max_length=255, verbose_name="ชื่อหมวดหมู่")
    content = models.TextField(default='ใส่เนื้อหาบทความ')
    slug = models.SlugField(max_length=200, default='ใส่ลิงค์บทความ ตัวอย่าง /your-post-content')
    parent = models.ForeignKey('self',blank=True, null=True ,related_name='children',on_delete=models.CASCADE)

    class Meta:
        unique_together = ('slug', 'parent',)    
        verbose_name_plural = "categories"  

    def __str__(self):                           
        full_path = [self.title]                  
        k = self.parent
        while k is not None:
            full_path.append(k.title)
            k = k.parent
        return ' -> '.join(full_path[::-1])


class Post(models.Model):
    id = models.AutoField
    category = models.ForeignKey('Category',on_delete=models.CASCADE)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    content_images = models.ImageField(default='media/noimg-l.jpg')
    title = models.CharField(max_length=200,unique=True,default='ใส่ชื่อบทความ')
    content = models.TextField(default='ใส่เนื้อหาบทความ')
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)
    post_viewcount = models.PositiveIntegerField(default=0,)
    slug = models.SlugField(max_length=200, default='ใส่ลิงค์บทความ ตัวอย่าง /your-post-content')
    status = models.IntegerField(choices=STATUS , default=1)


    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

    def get_cat_list(self):
        k = self.category # for now ignore this instance method

        breadcrumb = ["dummy"]
        while k is not None:
            breadcrumb.append(k.slug)
            k = k.parent
        for i in range(len(breadcrumb)-1):
            breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1])
        return breadcrumb[-1:0:-1]

和我的觀點.py

   def cat_list(request):
    categories = Category.objects.all()
    return render(request, 'blog/categories.html', {'categories': categories})

def category_detail(request, slug):
    category = get_object_or_404(Category, slug=slug)
    return render(request, 'blog/category_detail.html', {'category': category})

和我的 urls.py

    urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('createcontent/', views.create_post, name='create_post'),
    path('article/<slug:slug>/', views.post_detail, name='post_detail'),
    path('category/', views.cat_list, name='category'),
    path('category/<slug:slug>/', views.category_detail, name='category_detail'),

]

最后在我的模板中

    <h1> {{ categories.title }} </h1>
<div class="container">
    <div class="row">

        {% for post in categories %}
        <div class="column">
            <div class="card" style="width: 20rem;">
                <img class="card-img-top" src="{{ post.content_images.url }}" alt="{{ post.title }}">
                <div class="card-body">
                    <b><p class="card-text"> <a href="{% url 'post_detail' post.slug %}"> {{ post.categories.title }} </a></p></b>
                    <p> เขียนโดย {{ post.author }}</p>
                    <p class="card-text"> {{ post.content|safe|slice:":200" }}</p>
                    <div align="center"><button type="button" class="btn btn-outline-secondary"> <a href="{% url 'post_detail' post.slug %}">  อ่านเรื่องนี้ต่อ </a></button> </div>
                </div>
            </div>
        </div>
        {% endfor %}

    </div>
</div>

我嘗試在 Djangogirl 和其他網站上查找有關如何操作的信息,因為我想擁有自己的小型博客項目。 不想用 Wordpress

在您的詳細視圖中,您傳遞了一個名稱為categoryCategory object ,而不是categories 您可以使用{% for post in category.post_set.all %}遍歷帖子:

<h1> {{ category.title }} </h1>
<div class="container">
    <div class="row">
        {% for post in category.post_set.all %}
        <div class="column">
            <div class="card" style="width: 20rem;">
                <img class="card-img-top" src="{{ post.content_images.url }}" alt="{{ post.title }}">
                <div class="card-body">
                    <b><p class="card-text"> <a href="{% url 'post_detail' post.slug %}"> {{ post.categories.title }} </a></p></b>
                    <p>{{ post.author }}</p>
                    <p class="card-text"> {{ post.content|safe|slice:":200" }}</p>
                    <div align="center"><button type="button" class="btn btn-outline-secondary"> <a href="{% url 'post_detail' post.slug %}"></a></button> </div>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
</div>

一個ForeignKey [Django-doc] , django 在“目標 model ”中創建一個經理以相反的方向查詢。 如果不指定related_name=…參數 [Django-doc] ,則相關名稱是小寫的“目標模型”的名稱,以及一個_set后綴(這里是post_set ),這樣就可以查詢給定Category的相關Post

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM