Answer the question
In order to leave comments, you need to log in
Why doesn't django save comments?
Please help, when adding comments, the page is updated but the comments are not saved to the database, and if you do it through the shell, then everything is perfectly saved. I don't understand what the problem is.
models.py
class Comment(models.Model):
article = models.ForeignKey(Article, on_delete = models.CASCADE)
author_name = models.CharField('имя автора', max_length = 50)
comment_text = models.CharField('текст комментария', max_length = 200)
def __str__(self):
return self.author_name
app_name = 'base'
urlpatterns = [
path('', views.index, name = 'index'),
path('article/', views.article, name = 'article'),
path('article/<int:article_id>/', views.articles, name = 'articles'),
path('article/<int:article_id>/leave_comment/', views.leave_comment, name = 'leave_comment'),
path('promo/<int:article_id>/', views.promo, name = 'promo'),
path('article/<int:article_id>/leave_comment/', views.leave_comment, name = 'leave_comment')
]
def articles (request,article_id):
articles = Article.objects.get(id = article_id)
comment_list = articles.comment_set.all()
return render(request,'index/news.html',{'articles':articles,'comment_list':comment_list})
def leave_comment(request,article_id):
a = Article.objects.get(id = article_id)
a.comment_set.create(author_name = request.POST['name'], comment_text = request.POST['text'])
return HttpResponseRedirect(reverse('index:news',args = (a.id)))
<form actions="{% url 'base:leave_comment' articles.id %}" method = "post">
{% csrf_token %}
<input type="text" required placeholder = "Ваше имя" name ="name"><br>
<textarea name="text" required="" placeholder = "текст " cols="30" rows = "10"></textarea><br>
<button type = "submit">Оставить комментарий</button>
</form>
Answer the question
In order to leave comments, you need to log in
Can you point me to the documentation where it says that Foreign Key objects can be created like this "a.comment_set.create(author_name = request.POST['name'], comment_text = request.POST['text'])" ?
def leave_comment(request,article_id):
a = Article.objects.get(id = article_id)
comment = Comment(article=a, author_name= ... , comment_text=...)
comment.save()
....
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question