iT邦幫忙

2024 iThome 鐵人賽

DAY 22
0
Python

使用 Django 框架和 Wagtail,快速打造一個 CMS 網站系列 第 22

D22 - Wagtail API 的應用 - custom field query 特殊欄位

  • 分享至 

  • xImage
  •  

Wagtail API 模塊提供了一個公共的、只讀的、JSON 格式的 API,外部客戶端(如移動應用)或網站前端可以使用它。

昨天,已經完成了今天基本的 fetching content,照著做已經可以得到 images, pages,接下來,我們開始打造其他的 api 端點。

API 中的自訂頁面欄位
Wagtail 網站包含許多頁面類型,每個頁面類型都有其自己的欄位集。頁面端點默認只會公開常見欄位(例如標題和縮寫)。

若要通過 API 訪問自訂頁面欄位,請使用 ?type 參數選擇頁面類型。這將過濾結果,只包括該類型的頁面,但也會使該類型的所有導出自訂欄位在 API 中可用。

新增自訂頁面欄位

您可能需要通過 API 導出一些自訂欄位。這可以通過為每個頁面模型添加要導出的欄位列表到 api_fields 屬性中來實現。

我們打開 blog/models.py 開始加上 APIField

可以把整個 models.py 改成這樣

from django import forms
from django.db import models

from modelcluster.fields import ParentalKey, ParentalManyToManyField

# New imports added for ClusterTaggableManager, TaggedItemBase
# 要將 ClusterTaggableManager, TaggedItemBase 加進來
from modelcluster.contrib.taggit import ClusterTaggableManager
from taggit.models import TaggedItemBase

from wagtail.models import Page, Orderable
from wagtail.fields import RichTextField
from wagtail.admin.panels import FieldPanel, InlinePanel, MultiFieldPanel
from wagtail.search import index
from wagtail.snippets.models import register_snippet

from wagtail.api import APIField
from django.utils import timezone

# 加上 BlogPageTag 系統
class BlogPageTag(TaggedItemBase):
    content_object = ParentalKey("BlogPage", related_name="tagged_items", on_delete=models.CASCADE)

class BlogIndexPage(Page):
    intro = RichTextField(blank=True)

    def get_context(self, request):
        # Update context to include only published posts, ordered by reverse-chron
        context = super().get_context(request)
        blogpages = self.get_children().live().order_by("-first_published_at")
        context["blogpages"] = blogpages
        return context

    content_panels = Page.content_panels + [FieldPanel("intro")]

class BlogPage(Page):
    date = models.DateField("Post date")
    intro = models.CharField(max_length=250)
    body = RichTextField(blank=True)
    authors = ParentalManyToManyField("blog.Author", blank=True)
    tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
    published_date = models.DateTimeField(default=timezone.now)
    feed_image = models.ForeignKey("wagtailimages.Image", on_delete=models.SET_NULL, null=True, related_name="+")
    private_field = models.CharField(max_length=255, default="Default private value")

    search_fields = Page.search_fields + [
        index.SearchField("intro"),
        index.SearchField("body"),
    ]

    content_panels = Page.content_panels + [
        MultiFieldPanel(
            [
                FieldPanel("date"),
                FieldPanel("authors", widget=forms.CheckboxSelectMultiple),
                FieldPanel("tags"),
            ],
            heading="Blog information",
        ),
        FieldPanel("intro"),
        FieldPanel("body"),
        FieldPanel("published_date"),
        FieldPanel("feed_image"),
        InlinePanel("gallery_images", label="Gallery images"),
    ]

    api_fields = [
        APIField("published_date"),
        APIField("body"),
        APIField("feed_image"),
        APIField("authors"),  # 這將在 API 回應中嵌套相關的 BlogPageAuthor 物件
    ]

class BlogPageGalleryImage(Orderable):
    page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name="gallery_images")
    image = models.ForeignKey("wagtailimages.Image", on_delete=models.CASCADE, related_name="+")
    caption = models.CharField(blank=True, max_length=250)
    private_field = models.CharField(max_length=255, default="Default private value")

    panels = [
        FieldPanel("image"),
        FieldPanel("caption"),
    ]

@register_snippet
class Author(models.Model):
    name = models.CharField(max_length=255)

    api_fields = [
        APIField("name"),
    ]

    author_image = models.ForeignKey(
        "wagtailimages.Image",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )

    panels = [
        FieldPanel("name"),
        FieldPanel("author_image"),
    ]

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Authors"

class BlogTagIndexPage(Page):
    def get_context(self, request):
        # Filter by tag
        tag = request.GET.get("tag")
        blogpages = BlogPage.objects.filter(tags__name=tag)

        # Update template context
        context = super().get_context(request)
        context["blogpages"] = blogpages
        return context

這將使 published_date、body、feed_image 和一個包含 name 欄位的作者列表在 API 中可用。但是要訪問這些欄位,您必須在 API 本身使用 ?type 參數選擇 blog.BlogPage 類型。

因為動了 model.py

所以請下指令,進行 migrations

python manage.py makemigrations
python manage.py migrate

然後啟動 server

python manage.py runserver

接下來,就可以用 postman 來試試 custom field api

http://127.0.0.1:8000/api/v2/pages/?type=blog.BlogPage&fields=published_date,body

可以得到 json response

{
    "meta": {
        "total_count": 6
    },
    "items": [
        {
            "id": 6,
            "meta": {
                "type": "blog.BlogPage",
                "detail_url": "http://localhost/api/v2/pages/6/",
                "html_url": "http://localhost/blog/this/",
                "slug": "this",
                "first_published_at": "2024-08-11T00:32:22.132999Z"
            },
            "title": "This is 1st post",
            "published_date": "2024-09-26T15:27:58.443946Z",
            "body": "<p data-block-key=\"w2nch\">Welcome to my blog! This is my very first post, and what better way to start it than with a traditional \"Hello, world!\"? Today is a beautiful morning, and as I sit here typing, I'm filled with excitement about the journey we're about to embark on together through this blog. Here, I'll share my thoughts, experiences, and stories, hoping to connect with you and perhaps inspire. Thanks for joining me on this new adventure, and let's enjoy the beautiful mornings and the exciting moments that await us!</p>"
        },
        {
            "id": 7,
            "meta": {
                "type": "blog.BlogPage",
                "detail_url": "http://localhost/api/v2/pages/7/",
                "html_url": "http://localhost/blog/this-is-2nd-post/",
                "slug": "this-is-2nd-post",
                "first_published_at": "2024-08-11T00:33:38.571581Z"
            },
            "title": "This is 2nd post",
            "published_date": "2024-09-26T15:27:58.443946Z",
            "body": "<p data-block-key=\"mdh2z\">Welcome to the second entry in my 30-day blogging challenge! Today, I’m excited to delve into a series dedicated to exploring Django and Wagtail, two powerful tools that are shaping the future of web development. Over the next month, I will be posting daily, guiding you through the intricacies of Django, a high-level Python web framework that encourages rapid development and clean, pragmatic design. Alongside, we’ll discover Wagtail, a flexible Django content management system designed to streamline the process of managing rich, dynamic content. Join me on this educational journey as we unlock new potentials and practical applications of these frameworks in real-world scenarios. Stay tuned!</p>"
        },
        {
            "id": 8,
            "meta": {
                "type": "blog.BlogPage",
                "detail_url": "http://localhost/api/v2/pages/8/",
                "html_url": "http://localhost/blog/this-is-3rd-post/",
                "slug": "this-is-3rd-post",
                "first_published_at": "2024-08-11T00:34:54.771253Z"
            },
            "title": "This is 3rd post",
            "published_date": "2024-09-26T15:27:58.443946Z",
            "body": "<p data-block-key=\"tqj4l\">Welcome to the third post in my 30-day blogging series! Today, I’m excited to delve into a particularly powerful feature of Django: building RESTful APIs. Django, renowned for its simplicity and flexibility, also offers robust tools for creating APIs, which are crucial for modern web applications that need to communicate efficiently with other services and applications.</p><p data-block-key=\"b0itt\"></p><p data-block-key=\"13p2q\">In this post, I'll introduce Django REST framework (DRF), a popular toolkit that makes it easier to build Web APIs with Django. DRF is highly customizable and can handle complex data operations, making it an ideal choice for developers looking to expose their Django applications as RESTful interfaces.</p><p data-block-key=\"82ahs\"></p><p data-block-key=\"1f1on\">Over the course of this article, I'll cover:</p><p data-block-key=\"4rn9n\">- **Setting up Django REST Framework**: How to integrate DRF into your existing Django project.</p><p data-block-key=\"3aup4\">- **Creating your first API**: We'll walk through the process of defining serializers to convert Django models into JSON responses and setting up views that handle API requests.</p><p data-block-key=\"ktlo\">- **Authentication and permissions**: Ensuring that your API is secure and that only authorized users can access sensitive data.</p><p data-block-key=\"dpr25\"></p><p data-block-key=\"729op\">By the end of this post, you’ll have a foundational understanding of how to leverage Django’s capabilities to create powerful APIs that can expand the reach and functionality of your applications. Join me as we unlock the potential of Django in the world of APIs! Stay tuned for more insights each day of this series.</p>"
        },
        {
            "id": 9,
            "meta": {
                "type": "blog.BlogPage",
                "detail_url": "http://localhost/api/v2/pages/9/",
                "html_url": "http://localhost/blog/4th-post/",
                "slug": "4th-post",
                "first_published_at": "2024-08-11T06:50:51.253287Z"
            },
            "title": "4th post",
            "published_date": "2024-09-26T15:27:58.443946Z",
            "body": "<p data-block-key=\"0z7j2\">In my latest blog test, I’m exploring the subtle differences and rich histories of two beloved types of tea: green tea and black tea.</p><p data-block-key=\"dpace\"></p><p data-block-key=\"6u376\">**Green Tea:** Known for its delicate flavors and numerous health benefits, green tea originates from China and is made from Camellia sinensis leaves that have not undergone the same withering and oxidation process used to make black tea. This tea is celebrated for its antioxidant properties and has a lighter, more herbal taste than black tea.</p><p data-block-key=\"9h9g6\"></p><p data-block-key=\"4dj2m\">**Black Tea:** Often stronger in flavor, black tea is fully oxidized, which gives it a darker color and richer taste. Originating from both China and India, black tea is the basis for many popular blends including Earl Grey and English Breakfast. It’s known for its invigorating qualities and has a higher caffeine content than green tea.</p><p data-block-key=\"1fd33\"></p><p data-block-key=\"21hug\">Both teas offer unique flavors and health benefits, making them favorites among tea drinkers worldwide. Whether you prefer the robust profile of black tea or the subtle nuances of green tea, there’s no denying the timeless appeal of these beverages.</p>"
        },
        {
            "id": 10,
            "meta": {
                "type": "blog.BlogPage",
                "detail_url": "http://localhost/api/v2/pages/10/",
                "html_url": "http://localhost/blog/5th-article-bubble-tea/",
                "slug": "5th-article-bubble-tea",
                "first_published_at": "2024-08-11T08:05:35.978615Z"
            },
            "title": "5th article - Bubble tea",
            "published_date": "2024-09-26T15:27:58.443946Z",
            "body": "<p data-block-key=\"jcjjk\">**The Delightful World of Bubble Tea: An Introduction to Pearl Milk Tea**</p><p data-block-key=\"dvl29\"></p><p data-block-key=\"b6mpf\">Bubble tea, also affectionately known as pearl milk tea, has evolved from a local Taiwanese drink into a global sensation, captivating taste buds with its unique combination of flavors and textures. This popular beverage blends the rich, creamy texture of milk tea with the fun, chewy consistency of tapioca pearls, offering an experience that's both a drink and a snack.</p><p data-block-key=\"fv561\"></p><p data-block-key=\"1qdhk\">**Origins and Evolution**</p><p data-block-key=\"7bjur\">Pearl milk tea originated in Taiwan during the 1980s. The exact origin story varies, but it's generally believed that it was first created in a small tea shop where the owner decided to mix her sweetened tapioca pudding with her iced tea, sparking the trend that would sweep across Taiwan and, eventually, the world.</p><p data-block-key=\"2ifjo\"></p><p data-block-key=\"8j8m9\">**Ingredients and Variations**</p><p data-block-key=\"b7d4e\">The classic pearl milk tea consists of black tea, milk, sugar, and the star ingredient—tapioca pearls. These pearls are made from tapioca starch, derived from the cassava plant, and are known for their gummy bear-like texture. Over time, the variations have expanded to include a wide array of tea bases such as green tea, oolong, and even coffee. The milk component can be as varied, with options including whole milk, non-dairy milk, and flavored creams.</p><p data-block-key=\"608ea\"></p><p data-block-key=\"75enr\">In addition to the classic bubble tea, variations now include fruit-flavored teas, which are often topped with popping boba; these are tapioca pearls filled with fruit juices that burst in the mouth. Another popular variant is the cheese tea, topped with a thick, creamy layer of cheese foam, contrasting wonderfully with the tea's natural bitterness.</p><p data-block-key=\"1n808\"></p><p data-block-key=\"2krcm\">**Cultural Impact and Global Reach**</p><p data-block-key=\"8jj0b\">The spread of pearl milk tea beyond Taiwan began in the 1990s and has since become a fixture in many countries around the world. In cities from New York to Tokyo, it's common to see long lines of enthusiasts waiting to get their hands on this beloved beverage. The drink's customizable nature—allowing for adjustments in sugar levels, ice, and toppings—has endeared it to a global audience, each enjoying a personalized taste experience.</p><p data-block-key=\"b6j8g\"></p><p data-block-key=\"3dtq\">**Health Considerations**</p><p data-block-key=\"e7u3e\">While delicious, bubble tea is often high in calories and sugars, especially when additional toppings and sweeteners are added. Health-conscious individuals can opt for less sugar and fewer toppings, or choose green tea bases for a more antioxidant-rich drink.</p><p data-block-key=\"c6bhn\"></p><p data-block-key=\"8jje9\">**The Making of Bubble Tea**</p><p data-block-key=\"ago0f\">Making bubble tea at home can be a fun experiment. The essential ingredients include tea, tapioca pearls (available at Asian markets), milk, and sweetener. Cooking tapioca pearls to the right consistency requires attention, as they need to be boiled and then soaked in sugar syrup to achieve their signature sweetness and texture.</p><p data-block-key=\"cm0o1\"></p><p data-block-key=\"1n09o\">**Conclusion**</p><p data-block-key=\"dustu\">Pearl milk tea, with its delightful mix of textures and customizable flavors, is more than just a beverage; it's a cultural phenomenon that invites exploration and enjoyment. Whether you are a long-time fan or a curious newcomer, the world of bubble tea offers a vast landscape of flavors to explore and enjoy.</p>"
        },
        {
            "id": 11,
            "meta": {
                "type": "blog.BlogPage",
                "detail_url": "http://localhost/api/v2/pages/11/",
                "html_url": "http://localhost/blog/make-black-tea-from-tea-bag/",
                "slug": "make-black-tea-from-tea-bag",
                "first_published_at": "2024-08-11T08:09:57.752989Z"
            },
            "title": "Make black tea from tea bag",
            "published_date": "2024-09-26T15:27:58.443946Z",
            "body": "<p data-block-key=\"3lxi8\">**Exploring the Convenience and Charm of Black Tea Bags**</p><p data-block-key=\"6hs4b\"></p><p data-block-key=\"55bnd\">Black tea bags offer a simple and quick solution for tea enthusiasts around the world. Packed with flavor and history, these small packets are more than just a convenience—they are a testament to the evolution of tea consumption over centuries.</p><p data-block-key=\"4ad22\"></p><p data-block-key=\"22kua\">**History and Development**</p><p data-block-key=\"efj50\">The concept of the tea bag originated in the early 20th century, almost accidentally. It began when tea merchants started sending samples in small silk bags to their customers, who discovered they could brew the tea directly in the bag. The convenience was undeniable, and soon the tea bag was patented and began its journey to becoming a household staple. Originally made of silk, modern tea bags are typically crafted from paper, nylon, or other materials that are designed to withstand hot water while allowing the tea to infuse efficiently.</p><p data-block-key=\"bq4r5\"></p><p data-block-key=\"60rdk\">**Types of Black Tea in Tea Bags**</p><p data-block-key=\"9qlv8\">Black tea itself is known for its robust flavor and higher caffeine content compared to other types of tea. Common varieties include:</p><p data-block-key=\"4u2q7\"></p><p data-block-key=\"b3gva\">- **English Breakfast**: A blend of several black teas, usually including Assam, Ceylon, and Kenyan teas, known for its full-bodied richness.</p><p data-block-key=\"dapes\">- **Earl Grey**: Black tea flavored with bergamot oil, offering a distinctive citrus aroma and flavor.</p><p data-block-key=\"4ovb0\">- **Darjeeling**: Often referred to as the \"champagne of teas,\" this offers a lighter, musky sweetness with floral notes.</p><p data-block-key=\"eot8g\">- **Assam**: Known for its bold, malty flavor, it’s a popular choice for those who enjoy a hearty cup of tea.</p><p data-block-key=\"lu57\"></p><p data-block-key=\"57mq9\">**Benefits of Using Tea Bags**</p><p data-block-key=\"fjsmf\">Tea bags provide several advantages that make them a favored choice among many tea drinkers:</p><p data-block-key=\"dh8ca\"></p><ol><li data-block-key=\"7ma9u\">**Convenience**: Tea bags eliminate the need for measuring out loose-leaf tea and simplify the brewing process.</li><li data-block-key=\"d6koi\">**Consistency**: Each tea bag is pre-measured, which ensures a consistent taste and strength each time it is brewed.</li><li data-block-key=\"4vmah\">**Variety**: With tea bags, it’s easy to switch between different types of black tea or even different types of tea without having to clean out a tea infuser.</li><li data-block-key=\"41lp7\">**Portability**: Tea bags are easy to transport and use anywhere, making them ideal for travel or office environments.</li></ol><p data-block-key=\"36sfe\"></p><p data-block-key=\"cn87v\">**Environmental Considerations**</p><p data-block-key=\"8hg1m\">While tea bags offer undeniable convenience, they also come with environmental considerations. Traditional tea bags may contain plastics or other non-biodegradable materials. However, many companies are now producing fully biodegradable and compostable tea bags to address environmental concerns.</p><p data-block-key=\"vchq\"></p><p data-block-key=\"34odh\">**Making the Perfect Cup**</p><p data-block-key=\"66n0a\">To brew the perfect cup of black tea using a tea bag:</p><ol><li data-block-key=\"ffo37\">Boil fresh water. Black tea tastes best when made with water at a rolling boil.</li><li data-block-key=\"9n2f4\">Steep the tea bag in the hot water for 3 to 5 minutes, depending on how strong you like your tea.</li><li data-block-key=\"7hc9e\">Remove the tea bag and add milk, sugar, or lemon as desired.</li></ol><p data-block-key=\"1pb5b\"></p><p data-block-key=\"4g36u\">**Conclusion**</p><p data-block-key=\"34s4\">Black tea bags are a testament to the tradition and innovation within the tea industry. They offer a practical way to enjoy one of the world's oldest beverages. Whether you're at home, at work, or on the go, a tea bag is a simple solution for relishing a rejuvenating cup of black tea.</p>"
        }
    ]
}

上一篇
D21 - 使用 Wagtail 已內建的 Django REST Framework 做出 api endPoint
下一篇
D23 - 快速的在 admin panel 中做出日曆
系列文
使用 Django 框架和 Wagtail,快速打造一個 CMS 網站30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言