Python Django:在/ startthread /没有反向匹配

时间:2016-04-05 23:04:53

标签: python django

我正在尝试创建一个用户可以提交新讨论主题的表单,但每次提交表单时,Django都会发出以下错误:

NoReverseMatch at /startthread/
Reverse for 'post_detail' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

这是我的 views.py

@user_passes_test(lambda u: u.is_authenticated)
def add_post(request):
    form = PostForm(request.POST or None)

    if form.is_valid() and request.user.is_authenticated():
        try:
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect(reverse(post))
        except IntegrityError as e:
            pass
    else:
        print("INVALID")
        print(form.errors)

    return render_to_response('webapp/startthread.html', 
                              { 'form': form },
                              context_instance=RequestContext(request))

def view_post(request, slug):
    post = get_object_or_404(Post, slug=slug)
    form = CommentForm(request.POST or None)
    if form.is_valid():
        comment = form.save(commit=False)
        comment.post = post
        comment.save()
        request.session["name"] = comment.name
        request.session["email"] = comment.email
        request.session["website"] = comment.website
        return redirect(request.path)
    form.initial['name'] = request.session.get('name')
    form.initial['email'] = request.session.get('email')
    form.initial['website'] = request.session.get('website')
    return render_to_response('webapp/threadlist.html',
                              {
                                  'post': post,
                                  'form': form,
                              },
                              context_instance=RequestContext(request))

这是我的 urls.py

from django.conf.urls import url, patterns, include
from django.contrib import admin
from . import views

admin.autodiscover()

    urlpatterns = [
        url(r'^$', views.index, name='index'),
        url(r'^admin/', include(admin.site.urls)),
        url(r'^register/$', views.register, name='register'),
        url(r'^login/$', views.login, name='login'),
        url(r'^logout/$', views.Logout, name='logout'),
        url(r'^startthread/$', views.add_post, name='startthread'),
        url(r'^tinymce/', include('tinymce.urls'))
    ]

1 个答案:

答案 0 :(得分:1)

您没有为post_detail端点和view_post视图定义网址:

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^register/$', views.register, name='register'),
    url(r'^login/$', views.login, name='login'),
    url(r'^logout/$', views.Logout, name='logout'),
    url(r'^startthread/$', views.add_post, name='startthread'),

    # ADDED
    url(r'^thread/(?P<slug>[-\w]+)/$', views.view_post, name='post_detail'),

    url(r'^tinymce/', include('tinymce.urls'))
]

reverse()需要slug参数:

return redirect(reverse(post, kwargs={"slug": post.slug}))