How to do it...

Now, we will add the RSS feed to the music app:

  1. In the music app, create the feeds.py file and add the following content:
# myproject/apps/music/feeds.py
from
django.contrib.syndication.views import Feed
from django.urls import reverse

from .models import Song
from .forms import SongFilterForm


class SongFeed(Feed):
description_template = "music/feeds/song_description.html"

def get_object(self, request, *args, **kwargs):
form = SongFilterForm(data=request.GET)
obj = {}
if form.is_valid():
obj = {"query_string": request.META["QUERY_STRING"]}
for field in ["artist"]:
value = form.cleaned_data[field]
obj[field] = value
return obj

def title(self, obj):
the_title = "Music"
artist = obj.get("artist")
if artist:
the_title = f"Music by {artist}"
return the_title

def link(self, obj):
return self.get_named_url("music:song_list", obj)

def feed_url(self, obj):
return self.get_named_url("music:song_rss", obj)

@staticmethod
def get_named_url(name, obj):
url = reverse(name)
qs = obj.get("query_string", False)
if qs:
url = f"{url}?{qs}"
return url

def items(self, obj):
queryset = Song.objects.order_by("-created")

artist = obj.get("artist")
if artist:
queryset = queryset.filter(artist=artist)

return queryset[:30]

def item_pubdate(self, item):
return item.created
  1. Create a template for the song descriptions in the RSS feed:
{# music/feeds/song_description.html #}
{% load i18n %}
{% with song=obj %}
{% if song.image %}
<img src="{{ song.image.url }}" alt="{{ song }}" />
{% endif %}
{% if song.url %}
<a href="{{ song.url }}" target="_blank"
rel="noreferrer noopener">
{% trans "Check this song" %}
</a>
{% endif %}
{% endwith %}
  1. Plug in the RSS feed in the URL configuration of the app:
# myproject/apps/music/urls.py
from
django.urls import path

from .feeds import SongFeed
from .views import SongList, SongDetail

app_name = "music"

urlpatterns = [
path("", SongList.as_view(), name="song_list"),
path("<uuid:pk>/", SongDetail.as_view(), name="song_detail"),
path("rss/", SongFeed(), name="song_rss"),
]
  1.  In the template of the song list view, add a link to the RSS feed:
{# music/song_list.html #}

{% url "music:songs_rss" as songs_rss_url %}
<p>
<
a href="{{ songs_rss_url }}?{{ request.META.QUERY_STRING }}">
{% trans "Subscribe to RSS feed" %}
</a>
</
p>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.13.173