Django反向错误:NoReverseMatch [英] Django reverse error: NoReverseMatch

查看:191
本文介绍了Django反向错误:NoReverseMatch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了很多不同的帖子,但是他们都使用不同版本的django,或者似乎没有工作。这是我要做的:

I've looked at a lot of different posts, but they're all either working with a different version of django or don't seem to work. Here is what I'm trying to do:

urls.py(对于整个项目):

urls.py (for the entire project):

    from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
        url(r'^blog/', include('blog.urls', namespace="blog")),
        url(r'^admin/', include(admin.site.urls)),
    )

urls.py(针对应用程序):

urls.py (specific to the app):

urlpatterns = patterns ('' ,
url(r'^$', views.index, name='index'),

url(r'^(?P<slug>[\w\-]+)/$', views.posts, name="postdetail"),

)

views.py:

def index(request):
    posts = Post.objects.filter(published=True)
    return render(request,'blog/index.html',{'posts':posts})

def posts(request, slug):
    post = get_object_or_404(Post,slug=slug)
    return render(request, 'blog/post.html',{'post':post})

最后的模板:

 {% block title %} Blog Archive {% endblock %}

    {% block content %}
        <h1> My Blog Archive </h1>
        {% for post in posts %}
        <div class="post">
            <h2>
                <a href="{% url "postdetail" slug=post.slug %}">
                    {{post.title}}
                </a>
            </h2>
            <p>{{post.description}}</p>
            <p>
                Posted on
                <time datetime="{{post.created|date:"c"}}">
                    {{post.created|date}}
                </time>
            </p>
        </div>
        {% endfor %}
    {% endblock %}

由于某些原因这给了我一个没有反向匹配:反向'postdetail'与参数'()'和关键字参数'{u'slug':u'third'}'没有找到。 0模式尝试:[]

For some reason this gives me a "No reverse Match": Reverse for 'postdetail' with arguments '()' and keyword arguments '{u'slug': u'third'}' not found. 0 pattern(s) tried: []

我已经尝试摆脱了 postdetail 在模板中,我也尝试通过视图名称而不是模式名称来引用它。还没有运气文件也不是太有帮助。

I've already tried getting rid of the double quotes around postdetail in the template, and I've also tried referring to it by the view name instead of the pattern name. Still no luck. The documentation isn't too helpful either.

帮助非常感激!感谢

推荐答案

在包含URL时,您使用了一个命名空间,因此您可能需要使用博客:postdetail来反转它。

You've used a namespace when including the URLs, so you probably need to use "blog:postdetail" to reverse it.

这篇关于Django反向错误:NoReverseMatch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆