Django 2.0中/ blog /处的NoReverseMatch

时间:2018-11-19 06:00:34

标签: javascript python html css django

am在尝试设置博客类别页面时遇到此错误 / blog /中的NoReverseMatch 找不到带有参数“('',)”的“ category_detail”。尝试了1个模式:['blog \ / category \ -detail \ /(?P [-a-zA-Z0-9 _] +)$']

这是我的url.py

from django.urls import path,include
from .import views

urlpatterns = [
    path('blog/',views.post_list,name="post_list"),
    path('blog/post-detail/<slug:slug>',views.post_detail,name="post_detail"),
    path('blog/category-detail/<slug:slug>',views.category_detail,name="category_detail"),

]

views.py

from django.shortcuts import render,get_object_or_404
from.models import Post,Category

# Create your views here.
def post_list(request):
    object_list=Post.objects.all()
    context={
        'object_list': object_list,
    }
    return render(request,"blog.html",context)

def post_detail(request,slug=None):
    post=get_object_or_404(Post,slug=slug)
    context={
       'post':post,
    }
    return render(request,"post_detail.html",context)

def category_detail(request,slug=None):
    category=get_object_or_404(Category,slug=slug)
    post=Post.objects.filter(category=category,status='Published')
    context={
        'category':category,
        'post':post,
    }
    return render(request,"category_detail.html",context)

blog.html

{% for obj in object_list %}
    {% if obj.status == 'Published' %}
      <article>
        <div class="embed-responsive embed-responsive-16by9">
      <img src="images/blog1.jpg" alt="" />
      </div>
        <div class="post-content">

    <h2>{{obj.title}}</h2>

    <div>
    {{obj.created}}  Author {{obj.user}} <h4><a href="{% url 'category_detail' slug=post.category.slug %}">{{obj.Category}}</a></h4>
    <hr/>
    <p>{{obj.body}}</p>
    <a class="mtr-btn button-navy ripple" href= "{% url 'post_detail' obj.slug %}">Continue reading →</a><br>
    </div>
    </article>
    {% endif %}
{% endfor %}

category_detail.html

{% extends "base.html" %}
{% load static %}
{% block seo_title %}{{category.seo_title}}{% endblock %}
{% block seo_description %}{{category.seo_description}}{% endblock %}
{% block Content %}
<h2>{{category.title}}</h2>
<p>{{category.description}}</p>
{% for item in post %}
{{item.title}}
{{item.body|truncatechars:50}}
{% endfor %}
{% endblock Content %}

请注意其他观点。PY只是在使category_detail函数起作用

1 个答案:

答案 0 :(得分:0)

正如错误所述,此处缺少参数。也许您需要用docker-machine create myvm1来更改{% url 'category_detail' slug=post.Category.slug %},因为在{% url 'category_detail' slug=obj.category.slug %}模板中看不到任何post变量引用。

更新

您尚未共享模型代码,但是我假设您的blog.html模型具有Post模型的外键,并且看起来像Category。因此,您需要像这样更新视图:

Category=models.ForeignKey(Category)
相关问题