如何在Django中获取url变量?

时间:2014-01-17 17:55:39

标签: django url

我的views.py

中有类似内容
class CommentMixin(object):
    def get_context_data(self, **kwargs):
        context = super(MenuMixin, self).get_context_data(**kwargs)
        context['comments'] = Comments.objects.filter(post=xxxxxxxxxxxxx).order_by('-pub_date')
        return context
...

class PostDetailView(CommentMixin, generic.DetailView):
    model = models.Post

PostDetail = PostDetailView.as_view()
PostList = PostList.as_view()

comment.html的片段:

{% for comment in comments %}
    <article class="uk-comment">
    <header class="uk-comment-header">
        <img class="uk-comment-avatar" src="{%gravatar_url comment.email%}" alt="Avatar">
        <h4 class="uk-comment-title">{{comment.author}}</h4>
        <div class="uk-comment-meta">Dodano dnia {{comment.pub_date}}</div>
    </header>
    <div class="uk-comment-body">{{comment.content}}</div>
</article>

urls.py的片段:

url(r'^post/(?P<slug>[\w\-_]+)/$', 'page.views.PostDetail', name='post-detail'),

我想通过该页面上的帖子替换xxxxxxxxxxxxx。网址格式如下所示:

http://localhost:8000/post/my-post-name/

1 个答案:

答案 0 :(得分:0)

DetailView将对象存储在 self.object 中 在get_context_data中,您可以在过滤器中使用它:

context['comments'] = Comments.objects.filter(post=self.object).order_by('-pub_date')