NoReverseMatch at / blog /使用Django 2

时间:2018-02-06 19:37:55

标签: python django django-2.0

大家好我收到此错误: enter image description here

这是我的主要网址:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/',include('blog.urls',namespace='blog')),
]

我的博客/ url.py:

app_name = 'blog'

urlpatterns = [
    path('',views.PostListView.as_view(), name='post_list'),
    path('<int:year>/<int:month>/<int:day>/<int:post>',views.post_detail,name='post_detail'),
]

view.py:

class PostListView(ListView):
    queryset = Post.published.all()
    context_object_name = 'posts'
    paginate_by = 3
    template_name = 'blog/post/list.html'

    def post_list(request):
        posts = Post.published.all()
        return render(request, 'blog/post/list.html', {'posts': posts})

    def post_detail(request, year, month, day, post):
        post = get_object_or_404(Post, slug=post, 
        status='published',publish__year=year,publish__month=month,publish__day=day)
        return render(request, 'blog/post/detail.html', {'post': post})

list.html:

{% extends "blog/base.html" %}

{% block title %}My Blog{% endblock %}

{% block content %}
<h1>My Blog</h1>
{% for post in posts %}
    <h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
    <p class="date">Published {{ post.publish }} by {{ post.author }}</p>
    {{ post.body|truncatewords:30|linebreaks }}
{% endfor %}

{% include "pagination.html" with page=page_obj %}
{% endblock %}

我不知道代码有什么问题。我需要一些帮助。

1 个答案:

答案 0 :(得分:1)

错误可能在您的网址格式中 - post_detail网址格式中的最后一个关键字参数应为slug,而不是int

app_name = 'blog'

urlpatterns = [
    path('',views.PostListView.as_view(), name='post_list'),
    path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'),
]

另外,为了保持一致,请确保使用正斜杠结束URL模式。