svineet
svineet

Reputation: 1889

Django RSS feed according to category

I have a model Question -

class Question(models.Model):
    title = models.CharField(max_length=1024)
    content = models.TextField()
    answer = models.TextField()
    pub_date = models.DateTimeField(auto_now=True)
    category = models.CharField(max_length=512)
    flags = models.IntegerField()

    def __unicode__(self):
        return self.title

I have several cateogries according to which I want the RSS to be displayed. I saw the documentation and came up with this -

class CategoryFeed(Feed):

    def get_object(self, request, category):
        return Question.objects.filter(category__exact=1)[:1][0]

    def title(self, obj):
        return "The Quiz Machine: latest questions for category %s" % obj.category

    def link(self, obj):
        return '/rss/{0}'.format(obj.category)

    def description(self, obj):
        return "Question for category %s" % obj.category

    def items(self, obj):
        return Question.objects.filter(category__exact=obj.category).order_by('-pub_date')[:30]

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

    def item_link(self, item):
        return '/{0}/'.format(item.id)

But it gives me error when I'm accessing 'rss/physics' saying that 'list index out of range.
There is a physics question in the table. It is displayed on the index page already. I'm not understanding the documentation.
What am I doing wrong here?

Upvotes: 1

Views: 293

Answers (1)

karthikr
karthikr

Reputation: 99650

In your method:

def get_object(self, request, category):
    return Question.objects.filter(category__exact=1)[:1][0]

You have category__exact=1

which needs to be category__exact=category

That is:

def get_object(self, request, category):
    return Question.objects.filter(category__exact=category)[:1][0]

To make it more foolproof, I would do:

def get_object(self, request, category):
    qs = Question.objects.filter(category__exact=category)[:1]
    if qs:
        return qs[0]
    return None

Upvotes: 1

Related Questions