簡體   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