# Dokumentasi Django 5.2.8

# Kerangka kerja umpan perkongsian

Django comes with a high-level syndication-feed-generating framework for creating RSS and Atom feeds.

Untuk membuat umpan sindikasi apapun, semua anda harus lakukan adalah menulis kelas Python pendek. Anda dapat membuat sebanyak umpan anda inginkan.

Django also comes with a lower-level feed-generating API. Use this if you want to generate feeds outside of a web context, or in some other lower-level way.

## Kerangka kerja tingkat-tinggi

### Ikhtisar

Kerangka kerja membangkitkan-umpan tingkat-tinggi didukung oleh kelas `Feed` dan tunjuk kesebuah contoh dari itu dalam URLconf anda.

### Kelas-kelas `Feed`

Sebuah kelas `Feed` adalah sebuah kelas Python yang mewakili umpan persengkongkolan. Sebuah umpan dapat berupa sederhana (misalnya, sebuah umpan "situs berita", atau umpan dasar menampilkan masukan terakhir dari blog) atau lebih rumit (misalnya, sebuah umpan menampilkan semua masukan blog dalam sebuah kategori tertentu, dimana kategori adalah variabel).

Subkelas kelas-kelas umpan `django.contrib.syndication.views.Feed`. Mereka dapat berada dimana saka dalam dasar kode anda.

Instance dari kelas-kelas `Feed` adalah tampilan dimana dapat digunakan dalam URLconf anda.

### Sebuah contoh sederhana

Contoh sederhana ini, diambil daro hipotesa polisi melebihi situs berita menggambarkan sebuah umpan dari lima barang berita terakhir.

    from django.contrib.syndication.views import Feed
    from django.urls import reverse
    from policebeat.models import NewsItem

    class LatestEntriesFeed(Feed):
        title = "Police beat site news"
        link = "/sitenews/"
        description = "Updates on changes and additions to police beat central."

        def items(self):
            return NewsItem.objects.order_by("-pub_date")[:5]

        def item_title(self, item):
            return item.title

        def item_description(self, item):
            return item.description

        # item_link is only needed if NewsItem has no get_absolute_url method.
        def item_link(self, item):
            return reverse("news-item", args=[item.pk])

Untuk menghubungi URL ke umpan ini, taruh sebuah instance dari obyek Feed dalam URLconf anda. Sebagai contoh:

    from django.urls import path
    from myproject.feeds import LatestEntriesFeed

    urlpatterns = [
        # ...
        path("latest/feed/", LatestEntriesFeed()),
        # ...
    ]

Catatan:

- Subkelas kelas Feed `django.contrib.syndication.views.Feed`.

- `title`, `link` dan `description` berhubungan pada RSS standar unsur `<title>`, `<link>` dan `<description>`, masing-masing.

- `items()` is, a method that returns a list of objects that should be included in the feed as `<item>` elements. Although this example returns `NewsItem` objects using Django's object-relational mapper, `items()` doesn't have to return model instances. Although you get a few bits of functionality "for free" by using Django models, `items()` can return any type of object you want.

- Jika anda sedang membuat sebuah umpan Atom, daripada sebuah umoan RSS, setel atribut `subtitle` daripada atribut `description`. Lihat Publishing Atom and RSS feeds in tandem, nanti, untuk sebuah contoh.

Satu hal tersisa untuk dilakukan. Dalam sebuah umpan RSS, setiap `<item>` mempunyai sebuah `<title>`, `<link>` dan `<description>`. Kami butuh memberitahu kerangka kerja data apa untuk ditaruh kedalam unsur-unsur tersebut.

- Untuk isi dari `<title>` dan `<description>`, Django mencoba memanggil metode `item_title()` dan `item_description()` pada kelas `Mereka meloloskan sebuah parameter tunggal, ``item``, yaitu obyek itu sendiri. Ini adalah pilihan; secara awalan, perwakilan string dari obyek digunakan untuk keduanya.

  Jika anda ingin melalukan pembentukan khusus apapun untuk salah satu judul atau keterangan, Django templates dapat digunakan sebagai gantinya. Jalur-jalur mereka dapat ditentukan dengan atribut `title_template` dan `description_template` pada kelas `Feed`. Cetakan-cetakan dibangun untuk setiap barang dan dilewatkan dua cetakan variabel konteks:

  - `{{ obj }}` -- Obyek saat ini (satu dari obyek-obyek manapun anda kembalikan dalam `items()`).

  - `{{ site }}` -- Sebuah obyek `django.contrib.sites.models.Site` mewakili situs saat ini. Ini berguna untuk `{{ site.domain }}` atau `{{ site.name }}`. Jika anda tidak memiliki kerangka kerja situs Django terpasang, ini akan disetel menjadi sebuah obyek `RequestSite`. Lihat RequestSite section of the sites framework documentation untuk lebih.

  Lihat a complex example dibawah yang menggunakan cetakan gambaran.

  Feed.get_context_data(**kwargs)

    Ada juga cara melewatkan informasi tambahan ke cetakan judul dan keterangan, jika anda butuh memasok lebih dari dua variabel disebutkan sebelumnya. Anda dapat menyediakan penerapan anda dari metode `get_context_data` dalam subkelas `Feed` anda. Sebagai contoh:

        from mysite.models import Article
        from django.contrib.syndication.views import Feed

        class ArticlesFeed(Feed):
            title = "My articles"
            description_template = "feeds/articles.html"

            def items(self):
                return Article.objects.order_by("-pub_date")[:5]

            def get_context_data(self, **kwargs):
                context = super().get_context_data(**kwargs)
                context["foo"] = "bar"
                return context

  Dan cetakannya:

      Something about {{ foo }}: {{ obj.description }}

  Metode ini akan dipanggil satu per setiap barang dalam list dikembalikan oleh `items()` dengan argumen katakunci berikut:

  - `item`: barang saat ini. Untuk alasan kesesuaian kebelakang, nama dari variabel konteks ini adalah `{{ obj }}`.

  - `obj`: obyek dikembalikan oleh `get_object()`. Secara awalan ini tidak dibuka ke cetakan untuk menghindari kebingungan dengan `{{ obj }}` (lihat diatas), tetapi anda dapat menggunakan itu dalam penerapan anda dari `get_context_data()`.

  - `site`: situs saat ini seperti digambarkan diatas.

  - `request`: permintaan saat ini.

  Perilaku dari meniru `get_context_data()` yang dari generic views - anda seharusnya memanggil `super()` untuk mendapatkan konteks data dari kelas induk, tambah data anda dan kembalikan ke dictionari dirubah.

- ntuk menentukan isi dari `<link>`, anda memiliki dua pilihan. Untuk setiap barang dalam `items()`, Django pertama mencoba memanggil metode `item_link()` pada kelas `Feed`. Dalam cara sama pada judul dan keterangan, itu melewatkan itu sebuah parameter tunggal, `item`. Jika metode itu tidak ada, Django mencoba menjalankan metode `get_absolute_url()` pada obyek itu. Kedua `get_absolute_url()` dan `item_link()` harus mengembalikan URL barang sebagai sebuah string Python biasa. Ketika dengan `get_absolute_url()`, hasil dari `item_link()` akan disertakan langsung dalam URL, jadi anda bertanggungjawab untuk melakukan semua URL yang diperlukan mengutip dan merubah ke ASCII didalam metode itu sendiri.

### Sebuah contoh rumit

Kerangka kerja juga mendukung umpan kebih rumit, melalui argumen.

Sebagai contoh, sebuah situs jaringan dapat menawarkan sebuah umpan RSS pada kesalahan baru untuk setiap polisi dikalahkan dalam kota. Itu konyol untuk membuat kelas `Feed` terpisah untuk polisi kalah; itu akan melanggar DRY principle dan akan memasangkan data ke logika pemrograman. Sebagai gantinya, persengkongkolan kerangka kerja membiarkan anda mengakses argumen-argumen dilewatkan dari URLconf anda sehingga umpan dapat mengeluarkan barang berdasarkan pada informasi dalam URL umpan.

Polisi mengalahkan umpan dapat diakses melalui URL seperti ini:

- `/beats/613/rss/` -- Returns recent crimes for beat 613.

- `/beats/1424/rss/` -- Returns recent crimes for beat 1424.

Ini dapat cocok dengan baris URLconf seperti:

    path("beats/<int:beat_id>/rss/", BeatFeed()),

Seperti sebuah tampilan, argumen-argumen dalam URL dilewatkan ke metode `get_object()` bersama dengan obyek diminta.

Ini adalah kode untuk umpan kalah-khusus:

    from django.contrib.syndication.views import Feed

    class BeatFeed(Feed):
        description_template = "feeds/beat_description.html"

        def get_object(self, request, beat_id):
            return Beat.objects.get(pk=beat_id)

        def title(self, obj):
            return "Police beat central: Crimes for beat %s" % obj.beat

        def link(self, obj):
            return obj.get_absolute_url()

        def description(self, obj):
            return "Crimes recently reported in police beat %s" % obj.beat

        def items(self, obj):
            return Crime.objects.filter(beat=obj).order_by("-crime_date")[:30]

To generate the feed's `<title>`, `<link>` and `<description>`, Django uses the `title()`, `link()` and `description()` methods. In the previous example, they were string class attributes, but this example illustrates that they can be either strings or methods. For each of `title`, `link` and `description`, Django follows this algorithm:

- Pertama, itu mencoba memanggil semua metode, melewatkan argumen `obj`, dimana `obj` adalah obyek dikembalikan oleh `get_object()`.

- Kegagalan itu, itu mencoba memanggil metode tanpa argumen.

- Kegagalan itu, itu menggunakan atribut kelas.

Juga catat bahwa `items()` juga mengikuti algoritma sama -- pertama, itu mencoba `items(obj)`, kemudian `items()`, lalu akhirnya atribut kelas `items` (yang harus berupa list).

We are using a template for the item descriptions. It can be as minimal as this:

    {{ obj.description }}

Bagaimanapun, anda bebas menambahkan bentuk seperti diinginkan.

Kelas `ExampleFeed` dibawah memberikan dokumentasi penuh pada metode dan atribut dari kelas-kelas `Feed`.

### Menentukan jenis dari umpan

Seperti awalan, umpan-umpan dihasilkan dalam kerangka kerja ini menggunakan RSS 2.0.

Untuk merubah itu, tambah sebuah atribut `feed_type` ke kelas class:~django.contrib.syndication.views.Feed anda, seperti itu:

    from django.utils.feedgenerator import Atom1Feed

    class MyFeed(Feed):
        feed_type = Atom1Feed

Catat bahwa mensetel `feed_type` pada sebuah obyek kelas, bukan sebuah instance.

Saat ini jenis umpan tersedia adalah:

- `django.utils.feedgenerator.Rss201rev2Feed` (RSS 2.01. Awal.)

- `django.utils.feedgenerator.RssUserland091Feed` (RSS 0.91.)

- `django.utils.feedgenerator.Atom1Feed` (Atom 1.0.)

### Lampiran

Untuk menentukan penutup, seperti yang digunakan dalam membuat umpan podcast , gunakan kaitan `item_enclosures` atau, cara lain dan jika anda hanya mempunyai penutup tunggal per barang, kaitan `item_enclosure_url`, `item_enclosure_length`, dan `item_enclosure_mime_type`. Lihat kelas `ExampleFeed` dibawah untuk contoh penggunaan.

### Bahasa

Feeds created by the syndication framework automatically include the appropriate `<language>` tag (RSS 2.0) or `xml:lang` attribute (Atom). By default, this is `django.utils.translation.get_language()`. You can change it by setting the `language` class attribute.

### URL

The `link` method/attribute can return either an absolute path (e.g. `"/blog/"`) or a URL with the fully-qualified domain and protocol (e.g. `"https://www.example.com/blog/"`). If `link` doesn't return the domain, the syndication framework will insert the domain of the current site, according to your `SITE_ID setting`.

Umpan-umpan atom membutuhkan sebuah `<link rel="self">` yang menentukan tempat saat ini umpan. Kerangka kerja persengkongkolan mengumpulkan ini otomatis, menggunakan ranah dari situs saat ini menurut pada pengaturan `SITE_ID`.

### menerbitkan Atom dan umpan RSS secara berduaan

Some developers like to make available both Atom and RSS versions of their feeds. To do that, you can create a subclass of your `Feed` class and set the `feed_type` to something different. Then update your URLconf to add the extra versions.

Ini adalah contoh lengkap:

    from django.contrib.syndication.views import Feed
    from policebeat.models import NewsItem
    from django.utils.feedgenerator import Atom1Feed

    class RssSiteNewsFeed(Feed):
        title = "Police beat site news"
        link = "/sitenews/"
        description = "Updates on changes and additions to police beat central."

        def items(self):
            return NewsItem.objects.order_by("-pub_date")[:5]

    class AtomSiteNewsFeed(RssSiteNewsFeed):
        feed_type = Atom1Feed
        subtitle = RssSiteNewsFeed.description

Catatan

Dalam contoh ini, umpan RSS menggunakan `description` selagi umpan Atom menggunakan `subtitle`. Itu karena umpan Atom tidak menyediakan untuk tingkat-umpan "description", tetapi mereka melakukan menyediakan untuk "subtitle".

Jika anda menyediakan sebuah `description` dalam kelas `Feed` anda, Django tidak akan otomatis menaruh itu kedalam unsur `subtitle`, karens subjudul dan gambaran adalah tidak perlu hal sama. Sebagai gantinya, anda harus menentukan atribut `subtitle`.

In the above example, we set the Atom feed's `subtitle` to the RSS feed's `description`, because it's quite short already.

Dan menemani URLconf:

    from django.urls import path
    from myproject.feeds import AtomSiteNewsFeed, RssSiteNewsFeed

    urlpatterns = [
        # ...
        path("sitenews/rss/", RssSiteNewsFeed()),
        path("sitenews/atom/", AtomSiteNewsFeed()),
        # ...
    ]

### Acuan kelas `Feed`

class views.Feed

Contoh ini menggambarkan semua kemungkinan atribut dan metode untuk sebuah kelas `Feed`.

    from django.contrib.syndication.views import Feed
    from django.utils import feedgenerator

    class ExampleFeed(Feed):
        # FEED TYPE -- Optional. This should be a class that subclasses
        # django.utils.feedgenerator.SyndicationFeed. This designates
        # which type of feed this should be: RSS 2.0, Atom 1.0, etc. If
        # you don't specify feed_type, your feed will be RSS 2.0. This
        # should be a class, not an instance of the class.

        feed_type = feedgenerator.Rss201rev2Feed

        # TEMPLATE NAMES -- Optional. These should be strings
        # representing names of Django templates that the system should
        # use in rendering the title and description of your feed items.
        # Both are optional. If a template is not specified, the
        # item_title() or item_description() methods are used instead.

        title_template = None
        description_template = None

        # LANGUAGE -- Optional. This should be a string specifying a language
        # code. Defaults to django.utils.translation.get_language().
        language = "de"

        # TITLE -- One of the following three is required. The framework
        # looks for them in this order.

        def title(self, obj):
            """
            Takes the object returned by get_object() and returns the
            feed's title as a normal Python string.
            """

        def title(self):
            """
            Returns the feed's title as a normal Python string.
            """

        title = "foo"  # Hard-coded title.

        # LINK -- One of the following three is required. The framework
        # looks for them in this order.

        def link(self, obj):
            """
            # Takes the object returned by get_object() and returns the URL
            # of the HTML version of the feed as a normal Python string.
            """

        def link(self):
            """
            Returns the URL of the HTML version of the feed as a normal Python
            string.
            """

        link = "/blog/"  # Hard-coded URL.

        # FEED_URL -- One of the following three is optional. The framework
        # looks for them in this order.

        def feed_url(self, obj):
            """
            # Takes the object returned by get_object() and returns the feed's
            # own URL as a normal Python string.
            """

        def feed_url(self):
            """
            Returns the feed's own URL as a normal Python string.
            """

        feed_url = "/blog/rss/"  # Hard-coded URL.

        # GUID -- One of the following three is optional. The framework looks
        # for them in this order. This property is only used for Atom feeds
        # (where it is the feed-level ID element). If not provided, the feed
        # link is used as the ID.

        def feed_guid(self, obj):
            """
            Takes the object returned by get_object() and returns the globally
            unique ID for the feed as a normal Python string.
            """

        def feed_guid(self):
            """
            Returns the feed's globally unique ID as a normal Python string.
            """

        feed_guid = "/foo/bar/1234"  # Hard-coded guid.

        # DESCRIPTION -- One of the following three is required. The framework
        # looks for them in this order.

        def description(self, obj):
            """
            Takes the object returned by get_object() and returns the feed's
            description as a normal Python string.
            """

        def description(self):
            """
            Returns the feed's description as a normal Python string.
            """

        description = "Foo bar baz."  # Hard-coded description.

        # AUTHOR NAME --One of the following three is optional. The framework
        # looks for them in this order.

        def author_name(self, obj):
            """
            Takes the object returned by get_object() and returns the feed's
            author's name as a normal Python string.
            """

        def author_name(self):
            """
            Returns the feed's author's name as a normal Python string.
            """

        author_name = "Sally Smith"  # Hard-coded author name.

        # AUTHOR EMAIL --One of the following three is optional. The framework
        # looks for them in this order.

        def author_email(self, obj):
            """
            Takes the object returned by get_object() and returns the feed's
            author's email as a normal Python string.
            """

        def author_email(self):
            """
            Returns the feed's author's email as a normal Python string.
            """

        author_email = "test@example.com"  # Hard-coded author email.

        # AUTHOR LINK --One of the following three is optional. The framework
        # looks for them in this order. In each case, the URL should include
        # the scheme (such as "https://") and domain name.

        def author_link(self, obj):
            """
            Takes the object returned by get_object() and returns the feed's
            author's URL as a normal Python string.
            """

        def author_link(self):
            """
            Returns the feed's author's URL as a normal Python string.
            """

        author_link = "https://www.example.com/"  # Hard-coded author URL.

        # CATEGORIES -- One of the following three is optional. The framework
        # looks for them in this order. In each case, the method/attribute
        # should return an iterable object that returns strings.

        def categories(self, obj):
            """
            Takes the object returned by get_object() and returns the feed's
            categories as iterable over strings.
            """

        def categories(self):
            """
            Returns the feed's categories as iterable over strings.
            """

        categories = ["python", "django"]  # Hard-coded list of categories.

        # COPYRIGHT NOTICE -- One of the following three is optional. The
        # framework looks for them in this order.

        def feed_copyright(self, obj):
            """
            Takes the object returned by get_object() and returns the feed's
            copyright notice as a normal Python string.
            """

        def feed_copyright(self):
            """
            Returns the feed's copyright notice as a normal Python string.
            """

        feed_copyright = "Copyright (c) 2007, Sally Smith"  # Hard-coded copyright notice.

        # TTL -- One of the following three is optional. The framework looks
        # for them in this order. Ignored for Atom feeds.

        def ttl(self, obj):
            """
            Takes the object returned by get_object() and returns the feed's
            TTL (Time To Live) as a normal Python string.
            """

        def ttl(self):
            """
            Returns the feed's TTL as a normal Python string.
            """

        ttl = 600  # Hard-coded Time To Live.

        # STYLESHEETS -- Optional. To set, provide one of the following three.
        # The framework looks for them in this order.

        def stylesheets(self, obj):
            """
            Takes the object returned by get_object() and returns the feed's
            stylesheets (as URL strings or as Stylesheet instances).
            """

        def stylesheets(self):
            """
            Returns the feed's stylesheets (as URL strings or Stylesheet
            instances).
            """

        # Hardcoded stylesheets.
        stylesheets = ["/stylesheet1.xsl", "stylesheet2.xsl"]

        # ITEMS -- One of the following three is required. The framework looks
        # for them in this order.

        def items(self, obj):
            """
            Takes the object returned by get_object() and returns a list of
            items to publish in this feed.
            """

        def items(self):
            """
            Returns a list of items to publish in this feed.
            """

        items = ["Item 1", "Item 2"]  # Hard-coded items.

        # GET_OBJECT -- This is required for feeds that publish different data
        # for different URL parameters. (See "A complex example" above.)

        def get_object(self, request, *args, **kwargs):
            """
            Takes the current request and the arguments from the URL, and
            returns an object represented by this feed. Raises
            django.core.exceptions.ObjectDoesNotExist on error.
            """

        # ITEM TITLE AND DESCRIPTION -- If title_template or
        # description_template are not defined, these are used instead. Both are
        # optional, by default they will use the string representation of the
        # item.

        def item_title(self, item):
            """
            Takes an item, as returned by items(), and returns the item's
            title as a normal Python string.
            """

        def item_title(self):
            """
            Returns the title for every item in the feed.
            """

        item_title = "Breaking News: Nothing Happening"  # Hard-coded title.

        def item_description(self, item):
            """
            Takes an item, as returned by items(), and returns the item's
            description as a normal Python string.
            """

        def item_description(self):
            """
            Returns the description for every item in the feed.
            """

        item_description = "A description of the item."  # Hard-coded description.

        def get_context_data(self, **kwargs):
            """
            Returns a dictionary to use as extra context if either
            description_template or item_template are used.

            Default implementation preserves the old behavior
            of using {'obj': item, 'site': current_site} as the context.
            """

        # ITEM LINK -- One of these three is required. The framework looks for
        # them in this order.

        # First, the framework tries the two methods below, in
        # order. Failing that, it falls back to the get_absolute_url()
        # method on each item returned by items().

        def item_link(self, item):
            """
            Takes an item, as returned by items(), and returns the item's URL.
            """

        def item_link(self):
            """
            Returns the URL for every item in the feed.
            """

        # ITEM_GUID -- The following method is optional. If not provided, the
        # item's link is used by default.

        def item_guid(self, obj):
            """
            Takes an item, as return by items(), and returns the item's ID.
            """

        # ITEM_GUID_IS_PERMALINK -- The following method is optional. If
        # provided, it sets the 'isPermaLink' attribute of an item's
        # GUID element. This method is used only when 'item_guid' is
        # specified.

        def item_guid_is_permalink(self, obj):
            """
            Takes an item, as returned by items(), and returns a boolean.
            """

        item_guid_is_permalink = False  # Hardcoded value

        # ITEM AUTHOR NAME -- One of the following three is optional. The
        # framework looks for them in this order.

        def item_author_name(self, item):
            """
            Takes an item, as returned by items(), and returns the item's
            author's name as a normal Python string.
            """

        def item_author_name(self):
            """
            Returns the author name for every item in the feed.
            """

        item_author_name = "Sally Smith"  # Hard-coded author name.

        # ITEM AUTHOR EMAIL --One of the following three is optional. The
        # framework looks for them in this order.
        #
        # If you specify this, you must specify item_author_name.

        def item_author_email(self, obj):
            """
            Takes an item, as returned by items(), and returns the item's
            author's email as a normal Python string.
            """

        def item_author_email(self):
            """
            Returns the author email for every item in the feed.
            """

        item_author_email = "test@example.com"  # Hard-coded author email.

        # ITEM AUTHOR LINK -- One of the following three is optional. The
        # framework looks for them in this order. In each case, the URL should
        # include the scheme (such as "https://") and domain name.
        #
        # If you specify this, you must specify item_author_name.

        def item_author_link(self, obj):
            """
            Takes an item, as returned by items(), and returns the item's
            author's URL as a normal Python string.
            """

        def item_author_link(self):
            """
            Returns the author URL for every item in the feed.
            """

        item_author_link = "https://www.example.com/"  # Hard-coded author URL.

        # ITEM ENCLOSURES -- One of the following three is optional. The
        # framework looks for them in this order. If one of them is defined,
        # ``item_enclosure_url``, ``item_enclosure_length``, and
        # ``item_enclosure_mime_type`` will have no effect.

        def item_enclosures(self, item):
            """
            Takes an item, as returned by items(), and returns a list of
            ``django.utils.feedgenerator.Enclosure`` objects.
            """

        def item_enclosures(self):
            """
            Returns the ``django.utils.feedgenerator.Enclosure`` list for every
            item in the feed.
            """

        item_enclosures = []  # Hard-coded enclosure list

        # ITEM ENCLOSURE URL -- One of these three is required if you're
        # publishing enclosures and you're not using ``item_enclosures``. The
        # framework looks for them in this order.

        def item_enclosure_url(self, item):
            """
            Takes an item, as returned by items(), and returns the item's
            enclosure URL.
            """

        def item_enclosure_url(self):
            """
            Returns the enclosure URL for every item in the feed.
            """

        item_enclosure_url = "/foo/bar.mp3"  # Hard-coded enclosure link.

        # ITEM ENCLOSURE LENGTH -- One of these three is required if you're
        # publishing enclosures and you're not using ``item_enclosures``. The
        # framework looks for them in this order. In each case, the returned
        # value should be either an integer, or a string representation of the
        # integer, in bytes.

        def item_enclosure_length(self, item):
            """
            Takes an item, as returned by items(), and returns the item's
            enclosure length.
            """

        def item_enclosure_length(self):
            """
            Returns the enclosure length for every item in the feed.
            """

        item_enclosure_length = 32000  # Hard-coded enclosure length.

        # ITEM ENCLOSURE MIME TYPE -- One of these three is required if you're
        # publishing enclosures and you're not using ``item_enclosures``. The
        # framework looks for them in this order.

        def item_enclosure_mime_type(self, item):
            """
            Takes an item, as returned by items(), and returns the item's
            enclosure MIME type.
            """

        def item_enclosure_mime_type(self):
            """
            Returns the enclosure MIME type for every item in the feed.
            """

        item_enclosure_mime_type = "audio/mpeg"  # Hard-coded enclosure MIME type.

        # ITEM PUBDATE -- It's optional to use one of these three. This is a
        # hook that specifies how to get the pubdate for a given item.
        # In each case, the method/attribute should return a Python
        # datetime.datetime object.

        def item_pubdate(self, item):
            """
            Takes an item, as returned by items(), and returns the item's
            pubdate.
            """

        def item_pubdate(self):
            """
            Returns the pubdate for every item in the feed.
            """

        item_pubdate = datetime.datetime(2005, 5, 3)  # Hard-coded pubdate.

        # ITEM UPDATED -- It's optional to use one of these three. This is a
        # hook that specifies how to get the updateddate for a given item.
        # In each case, the method/attribute should return a Python
        # datetime.datetime object.

        def item_updateddate(self, item):
            """
            Takes an item, as returned by items(), and returns the item's
            updateddate.
            """

        def item_updateddate(self):
            """
            Returns the updateddate for every item in the feed.
            """

        item_updateddate = datetime.datetime(2005, 5, 3)  # Hard-coded updateddate.

        # ITEM CATEGORIES -- It's optional to use one of these three. This is
        # a hook that specifies how to get the list of categories for a given
        # item. In each case, the method/attribute should return an iterable
        # object that returns strings.

        def item_categories(self, item):
            """
            Takes an item, as returned by items(), and returns the item's
            categories.
            """

        def item_categories(self):
            """
            Returns the categories for every item in the feed.
            """

        item_categories = ["python", "django"]  # Hard-coded categories.

        # ITEM COPYRIGHT NOTICE (only applicable to Atom feeds) -- One of the
        # following three is optional. The framework looks for them in this
        # order.

        def item_copyright(self, obj):
            """
            Takes an item, as returned by items(), and returns the item's
            copyright notice as a normal Python string.
            """

        def item_copyright(self):
            """
            Returns the copyright notice for every item in the feed.
            """

        item_copyright = "Copyright (c) 2007, Sally Smith"  # Hard-coded copyright notice.

        # ITEM COMMENTS URL -- It's optional to use one of these three. This is
        # a hook that specifies how to get the URL of a page for comments for a
        # given item.

        def item_comments(self, obj):
            """
            Takes an item, as returned by items(), and returns the item's
            comments URL as a normal Python string.
            """

        def item_comments(self):
            """
            Returns the comments URL for every item in the feed.
            """

        item_comments = "https://www.example.com/comments"  # Hard-coded comments URL

## Kerangka kerja tingkat-rendah

Behind the scenes, the high-level RSS framework uses a lower-level framework for generating feeds' XML. This framework lives in a single module: django/utils/feedgenerator.py.

Anda menggunakan kerangka kerja ini pada milik anda, untuk pembangkitan umpan tingkat-rendah. Anda dapat juga membuat pembangkit umpan penyesuaian subkelas-subkelas untuk digunakan dengan pilihan `feed_type` `Feed`.

### Kelas-kelas `SyndicationFeed`

Modul `feedgenerator` megnandung kelas dasar:

- `django.utils.feedgenerator.SyndicationFeed`

dan beberapa subkelas:

- `django.utils.feedgenerator.RssUserland091Feed`

- `django.utils.feedgenerator.Rss201rev2Feed`

- `django.utils.feedgenerator.Atom1Feed`

Setiap dari ketiga kelas ini mengetahui bagaimana membangun jenis tertentu dari umpan sebagai XML. Mereka berbagi antarmuka ini:

`SyndicationFeed.__init__()`

  Awalkan umpan dengan direktori yang diberikan dari metadata, yang berlaku ke seluruh umpan. Argumen kata kunci yang dibutuhkan adalah:

  - `title`

  - `link`

  - `description`

  Ada juga banyak dari katakunci pilihan lain:

  - `language`

  - `author_email`

  - `author_name`

  - `author_link`

  - `subtitle`

  - `categories`

  - `feed_url`

  - `feed_copyright`

  - `feed_guid`

  - `ttl`

  - `stylesheets`

  Argumen kata kunci tambahan apapun anda lewatkan ke `__init__` akan disimpan dalam `self.feed` untuk digunakan dengan custom feed generators.

  All parameters should be strings, except for two:

  - `categories` harus berupa urutan string.

  - `stylesheets` should be a sequence of either strings or `Stylesheet` instances.

  Beware that some control characters are not allowed in XML documents. If your content has some of them, you might encounter a `ValueError` when producing the feed.

  Changed in Django 5.2:

  The `stylesheets` argument was added.

`SyndicationFeed.add_item()`

  Tambah sebuah barang ke umpan dengan parameter yang diberikan.

  Argumen kata kunci yang diwajibkan adalah:

  - `title`

  - `link`

  - `description`

  Argumen kata kunci pilihan adalah:

  - `author_email`

  - `author_name`

  - `author_link`

  - `pubdate`

  - `comments`

  - `unique_id`

  - `enclosures`

  - `categories`

  - `item_copyright`

  - `ttl`

  - `updateddate`

  Argumen kata kunci tambahan akan disimpan untuk custom feed generators.

  Semua parameter, jika diberikan, harus berupa string, kecuali:

  - `pubdate` seharusnya obyek `datetime` Python.

  - `updateddate` seharusnya obyek `datetime` Python.

  - `enclosures` harus berupa list dari instance `django.utils.feedgenerator.Enclosure` .

  - `categories` harus berupa urutan string.

`SyndicationFeed.write()`

  Keluaran umpan dalam penyandian diberikan ke outfile, yang adalah obyek seperti-berkas.

`SyndicationFeed.writeString()`

  Mengembalikan umpan sebagai string dalam penyandian yang diberikan.

For example, to create an Atom 1.0 feed and print it to standard output:

    >>> from django.utils import feedgenerator
    >>> from datetime import datetime
    >>> f = feedgenerator.Atom1Feed(
    ...     title="My Blog",
    ...     link="https://www.example.com/",
    ...     description="In which I write about what I ate today.",
    ...     language="en",
    ...     author_name="Myself",
    ...     feed_url="https://example.com/atom.xml",
    ... )
    >>> f.add_item(
    ...     title="Hot dog today",
    ...     link="https://www.example.com/entries/1/",
    ...     pubdate=datetime.now(),
    ...     description="<p>Today I had a Vienna Beef hot dog. It was pink, plump and perfect.</p>",
    ... )
    >>> print(f.writeString("UTF-8"))
    <?xml version="1.0" encoding="UTF-8"?>
    <feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
    ...
    </feed>

### Pembangkit umpan penyesuaian

Jika anda butuh menghasilkan bentuk umpan penyesuaian, anda mendapatkan sepasang pilihan.

Jika bentuk umpan sama sekali penyesuaian, anda akan ingin mensubkelaskan `SyndicationFeed` dan sama sekali mengganti metode `write()` dan `writeString()`.

Bagaimanapun, jika bentuk umpan adalah berputar dari RSS atau Atom (yaitu GeoRSS, iTunes podcast format Apple, dll.), anda mendapatkan pilihan lebih baik. Jenis-jenis ini dari umpan khususnya menambahkan unsur-unsur tambahan dan/atau atribut pada bentuk pokok, dan ada kumpulan dari metode yang `SyndicationFeed` panggil untuk mendapatkan atribut tambahan ini. Dengan demikian, anda dapat mensubkelaskan kelas pembangkit umpan sesuai (`Atom1Feed` atau `Rss201rev2Feed`) dan memperpanjang callback ini. mereka adalah:

`SyndicationFeed.root_attributes(self)`

  Mengembalikan atribut `dict` untuk menamabhkan ke unsur umpan akar (`feed`/`channel`).

`SyndicationFeed.add_root_elements(self, handler)`

  Callback untuk menambahkan unsur-unsur didalam akar unsur umpan (`feed`/`channel`). `handler` adalah sebuah `XMLGenerator` dari pustaka SAX Python siap-pakai; anda dapat memanggil metode pada itu untuk menambahkan dokumen XML dalam pengolahan.

`SyndicationFeed.item_attributes(self, item)`

  Mengembalikan sebuah atribut `dict` untuk menambahkan ke setiap unsur barang (`item`/`entry`). Argumen, `item`, adalah sebuah dictionary dari semua data dilewatkan ke `SyndicationFeed.add_item()`.

`SyndicationFeed.add_item_elements(self, handler, item)`

  Callback pada tambah untus pada setiap unsur barang (`item`/`entry`). `handler` dan `item` seperti diatas.

Peringatan

Jika anda menimpa apapund ari metode ini, pastikan memanggil metode super kelas sejak mereka menambah unsur-unsur persyaratan untuk setiap bentuk umpan.

Sebagai contoh, anda mungkin memulai menerapkan pembangkit umpan RSS iTunes seperti itu:

    class iTunesFeed(Rss201rev2Feed):
        def root_attributes(self):
            attrs = super().root_attributes()
            attrs["xmlns:itunes"] = "http://www.itunes.com/dtds/podcast-1.0.dtd"
            return attrs

        def add_root_elements(self, handler):
            super().add_root_elements(handler)
            handler.addQuickElement("itunes:explicit", "clean")

There's a lot more work to be done for a complete custom feed class, but the above example should demonstrate the basic idea.

### Feed stylesheets

New in Django 5.2.

If you wish to have your RSS feed render nicely in a browser, you will need to provide styling information for the XML file, typically in XSLT or CSS formats.

You can add this to your RSS feed by setting the `stylesheets` attribute on the feed class.

This can be a hardcoded URL:

    from django.contrib.syndication.views import Feed

    class FeedWithHardcodedStylesheet(Feed):
        stylesheets = [
            "https://example.com/rss_stylesheet.xslt",
        ]

You can also use Django's static files system:

    from django.contrib.syndication.views import Feed
    from django.templatetags.static import static

    class FeedWithStaticFileStylesheet(Feed):
        stylesheets = [
            static("rss_styles.xslt"),
        ]

Another option is to have a view in your project that renders the XSLT document. You can then link it like so:

    from django.contrib.syndication.views import Feed
    from django.urls import reverse_lazy

    class FeedWithStylesheetView(Feed):
        stylesheets = [
            reverse_lazy("your-custom-view-name"),
        ]

Django will normally try to guess the MIME type of the given URL based on its extension, but if that fails you can specify it using the `Stylesheet` class:

    from django.contrib.syndication.views import Feed
    from django.utils.feedgenerator import Stylesheet

    class FeedWithHardcodedStylesheet(Feed):
        stylesheets = [
            Stylesheet("https://example.com/rss_stylesheet", mimetype="text/xsl"),
        ]

Similarly, if you'd like to use a different `media` attribute than `screen` (Django's default), you can use the `Stylesheet` class again:

    from django.contrib.syndication.views import Feed
    from django.utils.feedgenerator import Stylesheet

    class FeedWithHardcodedStylesheet(Feed):
        stylesheets = [
            Stylesheet("https://example.com/rss_stylesheet.xslt", media="print"),
        ]

Any of these options can be combined when using multiple stylesheets:

    from django.contrib.syndication.views import Feed
    from django.utils.feedgenerator import Stylesheet

    class MultiStylesheetFeed(Feed):
        stylesheets = [
            "/stylesheet1.xsl",
            Stylesheet("/stylesheet2.xsl"),
        ]