简体   繁体   中英

NoReverseMatch at /post/new Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name

blog/urls.py

    #from django.contrib import admin
from django.urls import path,re_path
from . import views

app_name='blog'
urlpatterns =[
        path('about/',views.AboutView.as_view(),name='about'),
        path('',views.PostListView.as_view(),name='post_list'),
        path('post/(?P<pk>\d+)/$',views.PostDetailView.as_view(),name='post_detail'),
        path('post/new',views.CreatePostView.as_view(),name='post_new'),
        re_path('post/(?P<pk>\d+)/edit/',views.PostUpdateView.as_view(),name='post_edit'),
        re_path('post/(?P<pk>\d+)/remove/',views.PostDeleteView.as_view(),name='post_remove'),
        path('drafts/',views.DraftListView.as_view(),name='post_draft_list'),
        re_path('post/(?P<pk>\d+)/comment/',views.add_comment_to_post,name='add_comment_to_post'),
        re_path('comment/(?P<pk>\d+)/remove/',views.comment_remove,name='comment_remove'),
        re_path('post/(?P<pk>\d+)/publish/',views.post_publish,name='post_publish'),
        re_path('comment/(?P<pk>\d+)/approve/', views.comment_approve, name='comment_approve'),

]

views.py

from django.shortcuts import render,get_object_or_404,redirect
from django.utils import timezone
from blog.models import Comment,Post
from blog.forms import CommentForm,PostForm
from django.urls import reverse_lazy
from django.contrib.auth import authenticate, login
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.views.generic import (TemplateView,
                                ListView,DetailView,CreateView,UpdateView)


class AboutView(TemplateView):
template_name = 'about.html'


class PostListView(ListView):
model = Post

def get_queryset(self):
    return 
Post.objects.filter(published_date__lte=timezone.now()).order_by('-
published_date')


class PostDetailView(DetailView):
model = Post

class CreatePostView(LoginRequiredMixin,CreateView):
login_url='/login/'
redirect_field_name='blog/post_detail.html'
form_class = PostForm
model=Post



class PostUpdateView(LoginRequiredMixin,UpdateView):
    login_url='/login/'
    redirect_field_name='blog/post_detail.html'
    form_class = PostForm
    model=Post


class PostDeleteView(LoginRequiredMixin,DetailView):
    model=Post
    success_url = reverse_lazy('post_list')


class DraftListView(LoginRequiredMixin,ListView):
    login_url = '/login/'
    redirect_field_name = 'blog/post_list.html'
    model = Post

    def get_queryset(self):
        return Post.objects.filter(
        published_date__isnull=True).order_by ('created_date')

@login_required
def add_comment_to_post(request,pk):
    post=get_object_or_404(Post,pk=pk)
    if request.method =='POST':
        form=CommentForm(request.POST)
        if form.is_valid():
            comment=form.save(commit=False)
            comment.post=post
            comment.save()
            return redirect('post_detail',pk=post.pk)
    else:
        form=CommentForm()
    return render(request,'blog/comment_form.html',{'form':form})


@login_required
def comment_approve(request,pk):
    comment = get_object_or_404(Comment,pk=pk)
    comment.approve()
    return redirect('post_detail',pk=comment.post.pk)

@login_required
def comment_remove(request,pk):
    comment = get_object_or_404(Comment,pk=pk)
    post_pk = comment.post.pk
    comment.delete()
    return redirect('post_detail',pk=post_pk)

@login_required
def post_publish(request,pk):
    post = get_object_or_404(Post,pk=pk)
    post.publish()
    return redirect('post_detail',pk=pk)

post_detail.html

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

{% block content %}


        <h1 class='posttitle loader'>{{ post.title }}</h1>

        {% if post.published_date %}
            <div class="date postdate">
                {{ post.published_date }}
            </div>

        {% else %}
            <a class="btn btn-default" href="{% url 'post_publish' pk=post.pk %}">Publish</a>
        {% endif %}

      <p class='postcontent' >{{ post.text|safe|linebreaksbr }}</p>


      {% if user.is_authenticated %}
          <a class="btn btn-primary" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
          <a class="btn btn-primary" href="{% url 'post_remove' pk=post.pk %}"><span class="glyphicon glyphicon-remove"></span></a>
      {% endif %}



  <hr>
  <a class="btn btn-primary btn-comment" href="{% url 'add_comment_to_post' pk=post.pk %}">Add comment</a>
  <div class="container">


  {% for comment in post.comments.all %}
  <br>
      {% if user.is_authenticated or comment.approved_comment %}

              {{ comment.created_date }}
              {% if not comment.approved_comment %}
                  <a class="btn btn-default" href="{% url 'comment_remove' pk=comment.pk %}"><span class="glyphicon glyphicon-remove"></span></a>
                  <a class="btn btn-default" href="{% url 'comment_approve' pk=comment.pk %}"><span class="glyphicon glyphicon-ok"></span></a>
              {% endif %}

          <p>{{ comment.text|safe|linebreaks }}</p>
          <p>Posted by: <strong>{{ comment.author }}</strong></p>

      {% endif %}
  {% empty %}
      <p>No comments posted.</p>
  {% endfor %}
</div>

{% endblock %}

When I click on save button it gives me error

models.py error
 self.published_date=timezone.now()
    self.save()
def approve_comments(self):
    return self.comments.filter(approved_comments=True)
**def get_absolute_url(self):
    return reverse("post_detail",kwargs={'pk':self.pk})** ...
def __str__(self):
    return self.title

它在执行时显示错误

将错误显示为“找不到 'post_detail' 的反向。'post_detail' 不是有效的视图函数或模式名称。”

NoReverseMatch at /post/new
Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name.

urls.py

from django.contrib import admin
from django.urls import path,include
from blog import views
from django.contrib.auth import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('blog.urls')),
    path('accounts/login/', views.login, name='login'),
    path('accounts/logout/', views.logout, name='logout', kwargs={'next_page': '/'}),
]

in your project URLs path('',include('blog.urls', namespace="blog")),

Add namespace with include when using template tagging...

def get_absolute_url(self):
    return reverse("blog:post_detail",kwargs={'pk':self.pk})*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM