繁体   English   中英

Django 错误:NoReverseMatch at /Post/8 Reverse for 'comments' with arguments '('',)' not found

[英]Django error : NoReverseMatch at /Post/8 Reverse for 'comments' with arguments '('',)' not found

我正在处理我的项目我遇到了“评论”问题:当用户单击“查看”按钮从主页查看帖子时,我添加了评论作为一个部分。

Django 错误:NoReverseMatch at /Post/8 Reverse for 'comments' with arguments '('',)' not found. 尝试了 1 个模式:['Post/(?P[0-9]+)$']

视图.py 文件

def viewList(request, id):
item = Post.objects.get(id=id)
context = {
    'item': item,
    'comment_form': comment(),
    'comments': item.get_comments.all(),
}
return render(request, 'auctions/item.html', context)

@login_required
def comments(request, id):
     listing = Post.objects.get(id=id)
     form = comment(request.PSOT)
     newComment = form.save(commit=False)
     newComment.user = request.user
     newComment.listing = listing
     newComment.save()
return HttpResponseRedirect(reverse("listing", {'id': id}))

模型.py文件

class Post(models.Model):

# data fields
title = models.CharField(max_length=64)
textarea = models.TextField()

# bid
price = models.FloatField(default=0)
currentBid = models.FloatField(blank=True, null=True)

imageurl = models.CharField(max_length=255, null=True, blank=True)
category = models.ForeignKey(
    Category, on_delete=models.CASCADE, default="No Category Yet!", null=True,  blank=True)

creator = models.ForeignKey(User, on_delete=models.PROTECT)
watchers = models.ManyToManyField(
    User, blank=True, related_name='watched_list')
date = models.DateTimeField(auto_now_add=True)

# for activated the Category
activate = models.BooleanField(default=True)

def __str__(self):
    return f"{self.title} | {self.textarea} |  {self.date.strftime('%B %d %Y')}"

class Comment(models.Model):

body = models.CharField(max_length=100)
createdDate = models.DateTimeField(default=timezone.now)

# link to the post model
auction = models.ForeignKey(
    Post, on_delete=models.CASCADE, related_name="get_comments")

user = models.ForeignKey(User, on_delete=models.CASCADE)

status = models.BooleanField(default=True)

def __str__(self):
    return self.createdDate.strftime('%B %d %Y')

HTML文件

<!-- Comments -->
    <div class="comments">
        <p>Add a comment:</p>
        <div class="row">
            <div class="col-6">
                <form action="{% url 'comments' listing.id %}" method="post">
                    {% csrf_token %}
                    <div class="input-group">
                        {{ comment_form }}
                    </div>
                        <input type="submit" value="save" class="btn btn-outline-dark btn-sm m-1"/>
                </form>
            </div>
        {% for comment in comments %}
            <div class="col-4">
                Comments:
                <h4>Name: {{comment.user}}</h4>
                <h4>Content: {{comment.body}}</h4>
                <h4>Date: {{comment.createdDate}}</h4>
            </div>
        {% endfor %}
        </div>
    </div>

网址.py

from django.urls import path 
from . import views


urlpatterns = [
     path("", views.index, name="index"),
     path("login", views.login_view, name="login"),
     path("logout", views.logout_view, name="logout"),
     path("register", views.register, name="register"),
     path("category/", views.category, name="category"),
     path("Post", views.createList, name="createList"),
      #comment url
     path("Post/<str:id>", views.viewList, name="viewList"),
     path("Post/<int:id>", views.comments, name="comments"),
]

您将Post对象作为item传递给模板,因此您应该使用以下方法解析 URL:

<!--        use item not listing ↓  -->
<form action="{% url 'comments' item.id %}" method="post">
    …
</form>

您创建评论的视图也有一些错误:您应该使用request.POST ,而不是request.PSOT

from django.shortcuts import redirect

@login_required
def comments(request, id):
    if request.method == 'POST'
         form = comment(request.POST, request.FILES)
         if form.is_valid():
             form.instance.user = request.user
             form.instance.auction_id = id
             form.save()
    return redirect('viewList', id=id)

此外,您的comment表单应继承自ModelForm而不是Form

class comment(forms.ModelForm):

    class Meta:
        model = Comment
        fields = ('content',)
        widgets = {
            'content': forms.Textarea(attrs={"class": "form-control"})
        }

最后你的urls.py有两个(完全)重叠模式,你应该使用不同的 URL 来添加给定的评论:

urlpatterns = [
     # …
     #comment url
     path('Post/<int:id>', views.viewList, name='viewList'),
     path('Post/<int:id>/add', views.comments, name='comments'),
]

注意:通常FormModelForm…Form后缀结尾,以避免与模型的名称冲突,并明确我们正在使用form 因此,最好使用CommentForm而不是comment

暂无
暂无

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

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