与参数'(u'Animals',)'的'category'在/ Reverse匹配NoReverseMatch

时间:2019-03-14 15:07:30

标签: python django

有几个类似的问题,但是我仍然不知道如何解决我的代码。

当我运行服务器时,Django给我这个错误:

> Reverse for 'category' with arguments '(u'Animals',)' and keyword
> arguments '{}' not found. 0 pattern(s) tried: []

> Error during template rendering
>In template /home/joelramone/django/myblog/blog/templates/pages/home.html, 
error at line 0

这里是 urls.py

from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.views import static as django_static
from blog import views as blog_views


url(r'^admin/', admin.site.urls),
url(r'^$',  blog_views.home),
url(r'^post/(?P<single>[-\w]+)/$', blog_views.single, name='single'),
url(r'^category/(?P<category>[-\w]+)/$', blog_views.archive, name='category'),
url(r'^images/(?P<path>.*)/$', django_static.serve, {'document_root': settings.BAS_DIR + '/images'}),

这里是 models.py

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=150)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    category = models.ManyToManyField('blog.Category', blank=True, null=True)
    image = models.FileField(blank=True, upload_to='images')

    def __str__(self):
        return self.title


class Category(models.Model):
    title = models.CharField(max_length=150)
    slug = models.CharField(max_length=150)
    parent = models.ForeignKey('blog.Category', blank=True, null=True)

    @staticmethod
    def list_categories():
        return Category.objects.all()

    def __str__(self):
        return self.title

这里是 views.py

def home(request):
    post_list = Post.objects.all()
    paginator = Paginator(post_list, 1)
    page = request.GET.get('page')
    categories = Category.list_categories()

    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)
    return render(request, 'pages/home.html', {'posts': posts, 'categories': categories})


def single(request, single):
    single = Post.objects.get(id=single)
    context = {
        'post': single
    }
    return render(request, 'pages/single.html', context)


def archive(request, category):
    cat = Category.objects.get(slug=category)
    post_list = Post.objects.filter(category__pk=cat.id)
    paginator = Paginator(post_list, 1)
    page = request.GET.get('page')
    categories = Category.list_categories()

    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
       posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    return render(request, 'pages/archive.html', {'posts': posts, 'categories': categories, 'category': cat.title})

header.html和footer.html是引导程序代码。通过以下句子从home.html调用它:{%include'partial / header.html'%}和{%include'partial / footer.html'%}

这里是 home.html

{% include 'partial/header.html' %}

    <h1>
        Home
    </h1>
    <hr>
    <ul>
        {% for post in posts %}
        <li>
            <a href="{% url 'single' post.id %}">
                {{post.title}} - {{post.id}}

            </a>
        </li>
         {% endfor %}

    </ul>

    <div class="pagination">
        {% if posts.has_previous %}
            <a href="?page={{post.previous_page_number}}">
                 prev
             </a>
        {% endif %}
        {% if posts.has_next %}
            <a href="?page={{post.next_page_number}}">
                next
            </a>
        {% endif %}

        Page {{posts.number}} of {{posts.paginator.num_pages}}
    </div>
{% include 'partial/footer.html' %}

这里是 header.html

<!DOCTYPE html>
<html lang="en">

<head>

    <title>MyBlog</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">MyBlog</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">

                <li class="nav-item active">
                    <a href="/">Home
                    </a>
                </li>


                {% for category in categories %}
                <li class="nav-item">

                    <a class="nav-link" href="{% url 'category' category.slug %}">{{category.title}}</a>

                </li>
                {% endfor %}
            </ul>

        </div>
    </nav>

这是 footer.html

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>
</body>

</html>

0 个答案:

没有答案