开发者

Viewing subset of objects in Django, Views, URLs, Models

I know this is a very basic concept in Django, and I have tried the tutorial but it is not working. I am working on a comic book database with the models set like this (at least, a sample of two of the models):

Class Title(models.Model):
    title = models.CharField(max_length=256)
    vol = models.IntegerField("Vol.")
    slug = models.SlugField(blank=True, null=True) 
    #desc = models.CharField(max_length=256)   
    class Meta:
        ordering = ['title']
    def get_absolute_url(self):
        return "/comics2/title/%s" % self.slug        
    def __unicode__(self):
        return self.title


class Issue(models.Model):
    title = models.ForeignKey(Title)
    number = models.IntegerField(help_text="Enter the number only. Do not include the hashtag.")
    writer = models.ManyToManyField(Creator)

What I am trying to do is create a page that shows a list of all the issues within that Title.

But, I have it setup in the views like this:

class AstonishingXMenIssueListView(ListView):

    context_object_name = "astonishing_list"
    queryset 开发者_高级运维= Issue.objects.filter(title__title="Astonishing X-Men").order_by("number")
    template_name = "comics2/astonishing_list.html"

My urls.py look like this:

(r'^comics2/title/(?P<title_slug>[-\w]+)/$', AstonishingXMenIssueListView.as_view(
    )), 

Of course, going to /uncanny-xmen-v1/ shows the same thing as the Astonishing link above.

Obviously, this is not a practical way to list issues by title for future issues and titles, so I need it setup so that I don't have to individually do this. Now, I have tried following the Django generic views tutorial, but I got an index tuple error.

I've tried this, but it doesn't work. This is what gets me the index tuple error.

class IssuesByTitleView(ListView):

    context_object_name = "issues_by_title_list"
    template_name = "comics2/issues_by_title.html",

    def get_queryset(self):
        title = get_object_or_404(Title, title__iexact=self.args[0])
        return Issue.objects.filter(title=title)

Any ideas? And can someone please reply in baby-language, as I am new to Django and Python, so simply telling me to look at the Tutorial again isn't going to help. So, maybe writing out the code would help! Thanks!


Generally, your IssueByTitleView is the right way to do it. But as you use named groups in your URL regex (the (?P<title_slug>[-\w]+) part of your URL), you have to access the URL parameters through self.kwargs instead of self.args. Also, you have to filter on the slug field, not the title field:

title = get_object_or_404(Title, slug=self.kwargs['title_slug'])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜