我试图为我的Django博客应用创建一个评论功能,这样的评论工作正常,但我只能通过我的管理页面添加评论。然而,我希望用户能够在博客文章中添加评论。
评论模型 models.py
:
class Comment(models.Model):
post = models.ForeignKey('feed.Post', on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField(max_length=500)
date_posted = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.content
我试图在我的网站上添加基于类视图的注释功能 views.py
:
class CommentCreateView(CreateView):
model = Comment
fields = ['content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
在我看来 urls.py
我把评论路径加成了这样,它使用的是和博文一样的路径,这样用户就可以在同一个页面上添加评论,而评论发布后,他们仍然在文章的页面上。
urlpatterns = [
path('', login_required(PostListView.as_view()), name='feed-home'),
path('user/<str:username>/', login_required(UserPostListView.as_view()), name='user-feed'),
# Blog Post View
path('post/<int:pk>/', login_required(PostDetailView.as_view()), name='post-detail'),
# (NOT WORKING) Comment View
path('post/<int:pk>/', login_required(CommentCreateView.as_view()), name='post-detail'),
path('post/new/', login_required(PostCreateView.as_view()), name='post-create'),
path('post/<int:pk>/update', login_required(PostUpdateView.as_view()), name='post-update'),
path('post/<int:pk>/delete', login_required(PostDeleteView.as_view()), name='post-delete'),
path('about/', views.about, name='feed-about'),
]
对于我的其他表单,如登录、注册等。我已经使用了脆皮表单,我想我也可以在这里做同样的事情,所以我在我的博客文章下面添加了一个小表单。post_detail.html
{% extends "feed/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<!-- Post (works well!) -->
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-feed' object.author.username %}">{{ object.author }}</a>
<small class="text-muted">{{ object.date_posted|date:"d. F Y" }}</small>
{% if object.author == user %}
<div>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a>
</div>
{% endif %}
</div>
<h2 class="article-title">{{ object.title }}</h2>
<img class="post-image mb-2" src="{{ post.image.url }}" alt="">
<p class="article-content">{{ object.content }}</p>
{% for comment in post.comments.all %}
<div class="comment">
<div class="date">{{ comment.date_posted }}</div>
<strong>{{ comment.author }}</strong>
<p>{{ comment.content|linebreaks }}</p>
</div>
{% empty %}
<p>No comments here yet(remove later)</p>
{% endfor %}
<!-- Form for the Comments (not working yet) -->
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-secondary" type="submit">Post</button>
</div>
</form>
</div>
</article>
{% endblock content %}
另外,表格不能正确显示,它只显示按钮,但通常通过添加的 {{ form|crispy }}
文本字段是自动添加的。
现在,当我点击提交按钮时,我得到了一个HTTP 405错误,我不知道如何才能让这个工作。
我在网上做了一些研究,但无法找到与我的问题相关的任何东西。
这个url是造成问题的原因,为什么你需要在创建表单时使用pk。
path('post/<int:pk>/', login_required(CommentCreateView.as_view()), name='post-detail'),
如果你想用你的post-detail创建评论,你可以在post_detail_view里面写逻辑,就像下面的代码。
def tutorial_detail_view(request, lecture_id):
tutorial = get_object_or_404(Course, pk=lecture_id) # here we get the id and all its componenet associated with it
comments = Comment.objects.filter(course=tutorial, reply=None).order_by('-id') # here we are filtering the comment for the relevent post and getting the latest post at the top
# if the request is post than create a foprm object
if request.method == 'POST':
comment_form = CommentForm(request.POST or None)
# if the form is valid than get the comment content and than create a comment object with the course detail, user detail and the comments detail and save it
if comment_form.is_valid():
comment = request.POST.get('comment')
reply_id = request.POST.get('comment_id')
qs = None
# for reply we first get the comment id
# if there is reply than we get the reply id
if reply_id:
qs = Comment.objects.get(id=reply_id)# to knw the reply of that comment by getting the reply id to the comment id
comment = Comment.objects.create(course=tutorial, user=request.user, comment=comment, reply=qs)
comment.save()
return redirect('teacher-profile')
else:
comment_form = CommentForm()
context = {
'tutorial': tutorial,
'comments': comments,
'comment_form': comment_form,
}
return render(request, 'apps/lecture.html', context)
这样你就可以使用一个URL来渲染它。希望你能从中得到一些启发。