Комментарий не сохраняется в файле view.py
Коды (ниже) должны позволять пользователю комментировать пост/страницу. Таким образом, комментарий привязывается к этой странице. Но после события submit комментарий не сохраняется, следовательно, ничего не отображается, кроме комментариев со страницы администратора.
Функция, отображающая страницу и комментарий в view.py
def list_page(request, list_id):
if request.user.is_authenticated:
list_auction = Auction_listings.objects.get(id=list_id)
categories = Category.objects.get(id = list_id)
return render(request, "auctions/auc_details.html", {
"detail": list_auction,
"cats":categories,
"user": request.user,
"comments": list_auction.comment.all(),
})
else:
list_auction = Auction_listings.objects.get(id =list_id)
return render(request, "auctions/auc_details.html", {
"detail":list_auction
})
функция комментария в view.py
def comment(request, list_id):
if request.user.is_authenticated:
list_auction = get_object_or_404(Auction_listings, pk=list_id)
if request.method == "POST":
comment_form = forms.Create_comment(request.POST)
if comment_form.is_valid():
com_t = comment_form.save(commit=False)
com_t.comment = list_auction
com_t.comment_by = request.user
com_t.save()
print(com_t)
return HttpResponseRedirect(reverse("list_page", args=(list_auction.id,)))
return render (request,"auctions/auc_details.html", {
"detail": list_auction,
"user": request.user,
"comments": list_auction.comment.all(),
})
Route в urls.py
path("<int:list_id>/comment", views.comment, name="comment"),
КлассForm в form.py
class Create_comment(forms.ModelForm):
class Meta:
model = models.Comment
fields = ['comment']
Класс модели в models.py Комментарий модели
class Comment(models.Model):
comment_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="commentor", blank=False)
comment_on = models.ForeignKey( Auction_listings, related_name="comment", on_delete=models.CASCADE)
comment = models.CharField(max_length=600)
comment_date_published = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.comment}"
Модель страницы (auction_listings
)class Auction_listings(models.Model):
auc_title = models.CharField(max_length=50)
auc_details = models.CharField(max_length=250)
auc_price = models.IntegerField()
auc_date_published = models.DateTimeField(auto_now_add=True)
auc_created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator", blank=True)
auc_image = models.ImageField(default='rose.jpg', blank=True)
auctions = models.ManyToManyField(Category, blank= True, related_name="category")
def __str__(self):
return f"{self.auc_title}"
html страница
<form action="{% url 'comment' detail.id %}" method="POST">
{% csrf_token %}
<input type="text" name="text">
<input type="hidden" name="auction_id" value="{{detail.id}}">
<button type=" submit ">Create</button>
</form>
Я попытался изменить маршрут так, чтобы он выглядел следующим образом:
path("/comment/<int:list_id>", views.comment, name="comment"),
Пробовал. Но это ничего не изменило.
Буду признателен за любую помощь. Спасибо всем.
Если вы ожидаете, что комментарий будет присоединен к list_auction, между ними должна быть связь
com_t.comment_on = list_auction
ИЛИ
com_t.comment_on_id = list_auction.id
в вашем случае:
if comment_form.is_valid():
com_t = comment_form.save(commit=False)
com_t.comment = 'the text of comment'
com_t.comment_on = list_auction
com_t.comment_by = request.user
com_t.save()
print(com_t)
return HttpResponseRedirect(reverse("list_page", args=(list_auction.id,)))
ПРИМЕЧАНИЕ: Для лучшей отладки проверьте свою базу данных, чтобы увидеть, как хранятся данные
1. Вызовите Create_comment из form.py
def list_page(request, list_id):
if request.user.is_authenticated:
list_auction = Auction_listings.objects.get(id=list_id)
categories = Category.objects.get(id = list_id)
comment_form = forms.Create_comment()
return render(request, "auctions/auc_details.html", {
"detail": list_auction,
"cats":categories,
"user": request.user,
"comments": list_auction.comment.all(),
"com_form":comment_form,
})
else:
list_auction = Auction_listings.objects.get(id =list_id)
return render(request, "auctions/auc_details.html", {
"detail":list_auction
})
2 Вызовите ""com_form"" на шаблоне.
<form action="{% url 'comment' detail.id %}" method="POST">
{% csrf_token %}
{{com_form}}
<button type=" submit ">Create</button>
</form>