A
A
Adam_Loginov2021-06-05 02:07:57
Django
Adam_Loginov, 2021-06-05 02:07:57

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

url.py
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')
]


views.py
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)))


news.html template code
<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

1 answer(s)
T
tema_sun, 2021-06-05
@tema_sun

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()
    ....

Never work with raw data like request.POST['name'] or request.POST['text']. Create a form and validate data through it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question