Poprzedni wpis (django.forms mnie pokonało (przynajmniej trochę)) | Następny wpis (I hate this feeling)

Django feeds (twisted way)

Yesterday on #django-newbie IRC channel somebody asked, if it is possible to create syndication feed that gets items filtered by some parameter, that does not come from the URL, but comes from the request instead. Barely remembering my previous work with feeds I replied that there has to be some way to achieve such effect by wrapping feed view in custom view and manipulate call parameters. After long thinking I came to following code (tested and working):

Here's a snippet of the basic urlconf module before applying any changes:

feeds = {
    'label': feeds.LatestEntriesByUser,
}
urlpatterns = patterns('django.contrib.syndication.views',
    (r'^feeds/(?P<url>.*)/$', 'feed', {'feed_dict': feeds}),
)

Using this urlconf, everything that is requested from the /feeds url, is being served by default syndication framework's view, but for the sake of completeness I'll wrap the default view with my own, customized view function. To achieve this, the above urlconf line must be changed to:

(r'^feeds/(?P<url>.*)/$', myapp.views.feeds, {'feed_dict': feeds}),

Then comes my view function in myapp.views:

from django.contrib.syndication.views import feed as orig_feed
def feeds(request, url, feed_dict):
    username = request.user.username
    url = '%s/%s' % (url, username)
    return orig_feed(request, url, feed_dict)

As shown above, I'm modifying the url parameter to contain an extra bit: the username I got from request. In the case of the feed 'articles' and username 'joe', the url that gets passed to built-in view will be /feeds/articles/joe/. So how do I handle this extra bit in my feed class?

Not surprisingly, this case is described in Django documentation (did I say the docs for Django are awesome?) - the feeds reference has a chapter on advanced feeds that covers the exactly identical case. Following this example, I'll add get_object method to my LatestEntriesByUser class:

def get_object(self, bits):
    return Entry.objects.get(user__username=bits[0])

Obvious? No. Easy? Yes. Documented? Yes!

Komentarze (3)

#1 Konrad skomentował(-a) 12 października 2008 o 00:18

Ten język polski tak ewoluuje ;) Z dnia na dzień go nie poznaje

#2 jarek skomentował(-a) 12 października 2008 o 12:00

I never said I'll write only in Polish and this day has to come eventually. ;)

#3 Konrad skomentował(-a) 12 października 2008 o 12:58

True, true - but it's hard to make multi-lingual content in django;) In generic way.

Skomentujesz?

* 


* 


* oznacza pole wymagane

Technikalia

  • XP-Dev.com: Free Subversion Hosting
  • A Django joint.
  • Python powered