django模板中的年日期月

时间:2017-10-22 06:17:04

标签: python django

我有一个主页http://127.0.0.1:8000/home/,其中列出了每个博客帖子的摘要列表,每个摘要链接到完整的博客帖子页面,其中包含例如http://127.0.0.1:8000/home/blog/2017/10/14/的网址。具有年月和日的完整博客网址的模板工作正常但是我在主页上获得了NoReverseMatch:

使用关键字参数'{'年':2017,'月':10,'天':1}'找不到'view_blogpost_with_pk'。尝试过1种模式:['home / blog /(?P [0-9] {4})/(?P [0-9] {2})/(?P [0-9] {2} )/ $']

我不知道为什么它使用2017/10/01而不是正确的年月日。我想我从视图中遗漏了一些东西

以下是我的主页模板:

<div class = "container">
<div class = "col-md-10">
    <div class ="well">
    {% for p in allposts %}
        <a href="{% url 'home:view_blogpost_with_pk' year=p.date.year month=p.date.month day=p.date.day %}"><img src="{{MEDIA_URL}}/{{p.pic}}"></a>
        <h1 class="text-uppercase"><a href="{% url 'home:view_blogpost_with_pk'  year=p.date.year month=p.date.month day=p.date.day %}">
            {{p.title}}</a></h1>
        <h3 id ="smallicons">
        <i id ="user" class="fa fa-user" aria-hidden="true"></i>
        <a href="{% url 'accounts:view_profile_with_pk' pk=p.author.pk %}">
        {{p.author.username}}</a>
        <i id = "clock" class="fa fa-clock-o" aria-hidden="true"></i>{{p.date}}
        <i id = "comments" class="fa fa-comment" aria-hidden="true"></i>
        <a href= "{% url 'home:view_blogpost_with_pk' year=p.date.year month=p.date.month day=p.date.day %}">
        {{p.comment_set.count}} comments</a> </h3>
        <p>{{p.body|truncatewords:"50"}}<a id= "readmore" href="{% url 'home:view_blogpost_with_pk' year=p.date.year month=p.date.month day=p.date.day %}"> read more</a></p>
        <hr id = "horizontalrule">
        <br>
    {%endfor%}
    </div>

主页的网址:

url(r'^$', HomeView.as_view(), name = 'home'),

主页视图:

class HomeView(TemplateView):

    template_name = 'home/home.html'

    def get(self,request):

        all_posts = BlogPost.objects.all().order_by('-date')
        args = {'allposts' : all_posts}
        return render(request, self.template_name, args)

每个博文的网址:

url(r'^blog/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', BlogPostView.as_view(),name = 'view_blogpost_with_pk')

查看每篇博文:

class BlogPostView(TemplateView):
template_name = 'home/blog.html'

def get(self,request,year,month,day):
    blogpost = BlogPost.objects.get(date__year=year, date__month=month, date__day=day)
    form = BlogPostForm()
    comments = Comment.objects.filter(comment_body_id=blogpost).order_by('-date')
    c = comments.count()


    args = {'bpost': blogpost,'form':form,'comments':comments,'c':c}
    return render(request,self.template_name, args)

一直在摸我的头几天现在没有找到解决方案,但任何帮助都非常感激。

0 个答案:

没有答案