M
M
Misha Tarasov2020-08-11 18:41:17
Django
Misha Tarasov, 2020-08-11 18:41:17

Why can't I add comments on the site (python - django)?

Hello! Please help with the problem! In general, when adding comments on the site, nothing happens, i.e. I click on the add comment button and nothing happens and the comment text remains in this field, BUT then I decided to add comments through the admin panel, they were displayed on site. I had a url binding leave_comment, she was responsible for adding comments, I also had a view with this binding. I decided to change the name of the binding, but then I decided back, I did everything as it was, but comments are not added (I can’t add it through the site, if through the admin panel, then everything is normal and they are displayed), until I changed the name of the binding, everything was added !
Here is the urls.py(app) code:

from django.urls import path

from . import views 

app_name = 'articles'

urlpatterns = [
  path('', views.index, name = 'index'),
  path('<int:article_id>/', views.detail, name = 'detail'),
  path('<int:article_id>/leave_comment/', views.leave_comment, name = 'leave_comment')
]


Here is the code for views.py (apps)

from django.http import Http404,HttpResponseRedirect
from django.shortcuts import render 

from django.urls import reverse

from .models import Article, Comment

def index(request):
    test = Article.objects.order_by('-pub_date')[:5]
    return render(request,'articles/list.html',{'test':test})

def detail(request,article_id):
    try:    
        a = Article.objects.get(id = article_id)      
    except:
        raise Http404('Статьи не найдены')    

    test2 = a.comment_set.order_by('-id')[:10]

    return render(request,'articles/detail.html',{'article': a, 'test2<code lang="html">

</code>': test2})<code lang="html">

</code>

def leave_comment(request,article_id):
    try:    
        a = Article.objects.get(id = article_id)      
    except:
        raise Http404('Статьи не найдены')
    a.comment_set.create(author_name = request.POST['name'],comment_text = request.POST['text'])    

    return HttpResponseRedirect(reverse ('articles:detail', args = (a.id,)))


And here is the template code (detail.html):

{% extends 'base.html' %}

{% block title %}{{article.article_title}}{% endblock %}

{% block content %}

<h1>{{article.article_title}}</h1>

<h2>{{article.article_text}}</h2>

<em>{{article.pub_date}}</em> 
<hr>

{% if test2 %}
        {% for c in test2  %}
        <p>
            <strong>{{c.author_name}}</strong>
            <p>{{c.comment_text}}</p>
        {% endfor  %}    
        </p>
{% else %}
Комментарии не найдены!    
{% endif %}

<hr>

<form action="{% url 'articles:leave_comment' article.id %}" method="POST"></form>

    {% csrf_token %}

    <input type = 'text' required placeholder="Введите имя", name = 'name'><br>
    <textarea name="text" required placeholder="Текст комментария" id="" cols="30" rows="10"></textarea><br>
    <button type = 'submit'>Добавить комментарий</button>
</form>

{% endblock %}


PAGE CODE IN google
<!DOCTYPE html>

<html lang = 'en' >
<head>
    <meta charset="UTF-8">
    <title>Неудачный порт На ПК</title>
</head>
<body>
    

<h1>Неудачный порт На ПК</h1>

<h2>Студия признала, что анизотропная фильтрация на PC пока не работает, несмотря на присутствие в настройках графики соответствующего параметра. Решение этой проблемы имеет высокий приоритет для команды.

Ещё одна первоочередная проблема — на «некоторых системах» наблюдаются «кратковременные подвисания во время путешествий по миру, при обновлении элементов интерфейса или квестов, а также смене ракурса.</h2>

<em>10 августа 2020 г. 0:02</em> 
<hr>
    <p>
        <strong>Миша</strong>
        <p>Коммент</p>
        
    </p>


<hr>

<form action="/articles/2/leave_comment/" method="POST"></form>

    <input type="hidden" name="csrfmiddlewaretoken" value="P8NbB4mYZToyhDcA71DXOCUUgRlXAufhUPiRWT0yGznSFqUaiqLo5zhJ5Yzt9vPH">

    <input type = 'text' required placeholder="Введите имя", name = 'name'><br>
    <textarea name="text" required placeholder="Текст комментария" id="" cols="30" rows="10"></textarea><br>
    <button type = 'submit'>Добавить комментарий</button>
</form>

</body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-08-11
@tumbler

Open the network inspector in your browser and see what requests and where you go when you send a comment through the site.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question