[英]How to add comments on Python Django posts with logged in username?
請讓我知道我哪里出錯了? 視圖.py
class AddComment(LoginRequiredMixin, CreateView):
model = Comment
form_class = CommentForm
template_name = 'comment.html'
success_url = reverse_lazy('home')
def form_valid(self, form):
form.instance.name = self.request.user
form.instance.post_id = self.kwargs\['pk'\]
return super().form_valid(form)
這些表格寫得正確嗎? forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body', )
widgets = {
# 'name': forms.TextInput(attrs={'class': 'form-control'}),
'body': forms.Textarea(attrs={'class': 'form-control'}),
}
我應該對模型進行任何更改嗎? 模型.py
class Comment(models.Model):
post = models.ForeignKey(Post,
related_name='comments',
on_delete=models.CASCADE)
name = models.ForeignKey(
User,
on_delete=models.CASCADE,
)
body = models.TextField(max_length=240)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
這是讓用戶評論帖子並顯示自己的名字的評論部分? 評論.html
{% if not object.comments.all %}
<p>No comments yet...</p>
<a href="{% url 'comment' object.pk %}">Add one</a>
{% else %}
<a href="{% url 'comment' object.pk %}">Add Comment</a>
<br><br>
{% for comment in object.comments.all %}
<strong>{{ comment.name }} </strong> - <small>{{ comment.date_added }}</small>
<br>
{{ comment.body }}
<br><br>
<hr>
{% endfor %}
{% endif %}
這是 AddComment 類視圖的 URL。 網址.py
path('post/<int:pk>/comment/', AddComment.as_view(), name='comment'),][1]
您沒有明確說明您的代碼出了什么問題。 我想提出一些建議。 首先,
{% for comment in object.comments.all %}
...
{% endfor %}
您將此代碼塊放在 {% if not object.comments.all %}...{% endif %} 中,因此如果注釋部分不為空,它將不會顯示在模板上。
另外,這個鏈接:
<a href="{% url 'comment' object.pk %}">Add Comment</a>
應該打開一個Django 模板表單,用戶可以在其中填寫評論。 之后,在表單的 POST 請求中,它會將評論數據發送到您在表單的action參數中放置的 URL,如下所示:
<form action="{% url 'comment' post.pk %}" method="post">
[Comment code here]
</form>
這將鏈接到您提供的此 URL:
path('post/<int:pk>/comment/', AddComment.as_view(), name='comment'),]
如果您也可以在 views.py 中提供您的代碼,以便更輕松地追蹤出錯的地方,那就更好了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.