簡體   English   中英

無法在我的 Django 博客上添加評論

[英]Unable to add a comment on my Django blog

我一直在嘗試在我的網站上向論壇添加評論,並且我已經成功地進入了能夠看到評論表單的階段。 但是,當您實際提交評論表單時,我收到以下錯誤。

僅供參考,“2020 年有哪些好的營銷活動?” 是我要添加評論的帖子的名稱。

在此處輸入圖像描述

以下是使用的模型:

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments')
    user_name = models.CharField(max_length=250)
    email = models.EmailField()
    content = models.TextField()
    created_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.user_name

class Post(models.Model):
    creator_id = models.ForeignKey(User, null=False, default=1)
    title = models.CharField(max_length=200)
    content = models.TextField()
    created_date = models.DateTimeField(auto_now_add=True)
    published_date = models.DateTimeField(blank=True, null=True, default=timezone.now)
    views = models.IntegerField(default=0)
    category = models.CharField(choices=CATEGORY_CHOICES, max_length=30, blank=True, null=True)
    image = models.ImageField(upload_to="img", blank=True, null=True)

    def __str__(self):
        return self.title

這是使用的視圖:

def comment_post_form(request, pk):
    """ Create a view that allows us to add a comment """

    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentPostForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('forum_post_details.html', {'post': post})
    else:
        form = CommentPostForm()
        return render(request, 'comment_post_form.html', {'form': form})

這是使用的表格:

class CommentPostForm(forms.ModelForm):

    class Meta:
        model = Comment
        fields = ['content']

這是模板中使用的“for”語句:

{% for comment in comments %}
            <p>{{ comment.created_date }}</p>
            <p>{{ comment.user_name }}</p>
            <p>{{ comment.content }}</p>
            {% empty %}
            <p>No comments added. Why not be the first!</p>
            {% endfor %}

非常感謝任何幫助,如果您需要其他任何幫助,請告訴我:)

你重定向的方式不是你如何做的。 您可以通過多種方式使用 redirect() function。

url.py

path('teacherprofile/', views.teacher_profile_view, name='teacher-profile'),

視圖.py

通過傳遞視圖的名稱

return redirect('teacher-profile')

通過傳遞一個硬編碼的 URL 重定向到:

return redirect(teacherprofile/)

這也適用於完整的 URL:

 return redirect('https://example.com/')

這樣,用戶將重定向 html 頁面本身。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM