繁体   English   中英

如何处理 Django 中的 NoReverseMatch 错误

[英]How to deal with NoReverseMatch Error in Django

我在下面遇到此错误:Reverse for 'post_detail' with no arguments not found。 尝试了 1 种模式:['(?P[-a-zA-Z0-9_]+)/$']。

我正在开发一个博客应用程序。 当您在索引页面的仪表板上单击查看更多文章时,post_detail.html 应显示完整文章并允许用户发表评论。 单击查看文章后,我不断收到上面发布的错误。

这是 post_detail.html 代码

{% extends 'base.html' %}
{% load crispy_forms_tags %}
 {% block content %}


<div class="container">
  <div class="row">
    <div class="col-md-8 card mb-4  mt-3 left  top">
      <div class="card-body">
        <h1>{% block title %} {{ post.title }} {% endblock title %}</h1>
        <p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p>
        <p class="card-text ">{{ post.content | safe }}</p>
      </div>
    </div>


    <div class="col-md-8 card mb-4  mt-3 ">
      <div class="card-body">
        <!-- comments -->
        {% with comments.count as total_comments %}
        <h2>{{ total_comments }} comments</h2>

        <p>
          {% endwith %} {% for comment in comments %}
        </p>

        <div class="comments" style="padding: 10px;">
          <p class="font-weight-bold">
            {{ comment.name }}
            <span class=" text-muted font-weight-normal">
              {{ comment.created_on }}
            </span>
          </p>
          {{ comment.body | linebreaks }}
        </div>

        {% endfor %}
      </div>
    </div>
    <div class="col-md-8 card mb-4  mt-3 ">
      <div class="card-body">
        {% if new_comment %}
        <div class="alert alert-success" role="alert">
          Your comment is awaiting moderation
        </div>
        {% else %}
        <h3>Leave a comment</h3>
        <form method="POST" action="{% url 'post_detail' %}" style="margin-top: 1.3em;">
          {{ comment_form | crispy }}
          {% csrf_token %}
          <button type="submit" class="btn btn-primary  btn-lg">Submit</button>
        </form>
        {% endif %}
      </div>
    </div>
  </div>
</div>

{% endblock content %}

我的模型

STATUS = (
    (0,"Draft"),
    (1,"Publish")
)
class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True, blank= True, null=True)
    updated_on = models.DateTimeField(auto_now= True)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)
    status = models.IntegerField(choices=STATUS, default=0)

    class Meta:
        ordering = ['-published_date']

    def publish(self):
        self.published_date=timezone.now()
        self.save()

    def __str__(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        return 'Comment {} by {}'.format(self.body, self.name)

查看 post_detail

def post_detail(request, slug):
    template_name = 'post_detail.html'
    post = get_object_or_404(Post, slug=slug)
    comments = post.comments.filter(active=True)
    new_comment = None
    # Comment posted
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():

            # Create Comment object but don't save to database yet
            new_comment = comment_form.save(commit=False)
            # Assign the current post to the comment
            new_comment.post = post
            # Save the comment to the database
            new_comment.save()
    else:
        comment_form = CommentForm()
    context = {'post': post,
                'comments': comments,
                'new_comment': new_comment,
                'comment_form': comment_form}

    return render(request, 'blog/post_detail.html', context)

url

urlpatterns = [
    path('', views.index, name='index'),
    #path('', views.PostList.as_view(), name='index'),
    path('login', views.login, name= 'login'),
    path('logout', views.logout, name= 'logout'),
    path('register', views.register, name = 'register'),
    path('dashboard', views.dashboard, name = 'dashboard'),
    path('posts', views.posts, name = 'posts'),
    path('articles', views.articles, name='articles'),
    path('prayers', views.prayers,name='prayers' ),
    path('prayer_request', views.prayers, name='prayer_request'),
    path('<slug:slug>/', views.post_detail, name='post_detail'),

    path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='registration/password_change_done.html'), 
        name='password_change_done'),

    path('password_change/', auth_views.PasswordChangeView.as_view(template_name='registration/password_change.html'), 
        name='password_change'),

    path('password_reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_done.html'),
     name='password_reset_done'),

    path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
    path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'),

    path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'),
     name='password_reset_complete'),
]

请帮助解决此错误。

在你的 urls.py 之后,你应该沿着你的 post_detail url 传递一个 slug。 所以在你的表单中,你不能调用你的 url 没有像这样<form method="POST" action="{% url 'post_detail' %}">

因为你不能轻易知道你的新帖子的 id,也许应该创建一个不同的 url 来创建一个新帖子,比如 post_create

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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