((DJANGO)NoReverseMatch at post /

问题描述 投票:0回答:1

我正在尝试在Django博客中实现评论表单。我正在阅读本教程(https://djangocentral.com/creating-comments-system-with-django/),但最后发生了错误。错误页面说:

/ post / firstpost /处的NoReverseMatch

找不到带有参数'(',)'的'user-posts'的反向。 1个尝试过的模式:['user \ /(?P [^ /] +)$']

enter image description here

urls.py

from django.urls import path
from django.conf.urls import include, url
from . import views
from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView

urlpatterns = [
    #Blog section
    path("", PostListView.as_view(), name='blog-home'),
    path("user/<str:username>", UserPostListView.as_view(), name='user-posts'),
    path('post/<slug:slug>/', views.post_detail, name='post-detail'),
    path("posts/new/", PostCreateView.as_view(), name='post-create'),
    path("post/<slug:slug>/update/", PostUpdateView.as_view(), name='post-update'),
    path("post/<slug:slug>/delete/", PostDeleteView.as_view(), name='post-delete'),
    path("about/", views.about, name="blog-about"),
    path("<category>/", views.blog_category, name="blog_category"),
]

models.py

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)

forms.py

from .models import Comment
from django import forms

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('name', 'email', 'body')

admin.py

from django.contrib import admin
from .models import Post, Category, Comment

class CategoryAdmin(admin.ModelAdmin):
    pass


@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    list_display = ('name', 'body', 'post', 'created_on', 'active')
    list_filter = ('active', 'created_on')
    search_fields = ('name', 'email', 'body')
    actions = ['approve_comments']

    def approve_comments(self, request, queryset):
        queryset.update(active=True)

admin.site.register(Post)
admin.site.register(Category, CategoryAdmin)

views.py

def post_detail(request, slug):
    template_name = 'blog/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()

    return render(request, template_name, {'post': post,
                                           'comments': comments,
                                           'new_comment': new_comment,
                                           'comment_form': comment_form})

post_detail.html

<article class="media content-section">

    <div class="card-body">
       <!-- comments -->
       <h2>{{ comments.count }} comments</h2>

       {% for comment in comments %}
       <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 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" style="margin-top: 1.3em;">
           {{ comment_form.as_p }}
           {% csrf_token %}
           <button type="submit" class="btn btn-primary  btn-lg">Submit</button>
         </form>
         {% endif %}
      </div>

    </article>

需要帮助。

django django-models django-forms django-views django-urls
1个回答
0
投票

在您的urls.py定义中,使用

path("user/<slug:username>", UserPostListView.as_view(), name='user-posts')

代替

path("user/<str:username>", UserPostListView.as_view(), name='user-posts')

取决于document

  • str-匹配任何非空字符串,但路径分隔符'/'除外。如果表达式中未包含转换器,则为默认设置。
  • slug-匹配由ASCII字母或数字以及连字符和下划线字符组成的任何条形字符串。例如,建立您的1st-django网站。
© www.soinside.com 2019 - 2024. All rights reserved.