Page not found after submitting form django

Viewed 42

I have a comment model in my forum and when I try to submit it it says:

 "Page not found - /POST?csrfmiddlewaretoken".

views.py:

@login_required
def comment(request, pk):
    if request.method == 'POST':
        form = CommentCreationForm(data=request.POST)
        if form.is_valid():
            comment.post = get_object_or_404(Post, pk=pk)
            comment.writer = request.user
            comment = form.save()
            messages.info(request, 'comment published')
            return JsonResponse({'message': 'Thank you for your comment'}, safe=False)
    else:
        form = CommentCreationForm()

html file:

<form action="POST"> {% csrf_token %}
  {{ form.text.errors }}
   <label for="{{ form.text.id_for_label }}">comment:</label>
   {{ form.text }}
   <button id="comment" type="submit">comment</button>
</form>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

urls.py:

path('<int:pk>/comment/', views.comment, name='comment'),

By the way, can you help me make it in ajax?

1 Answers

You have to add url to the attribute action and POST to method attribute:

<form action="{% url 'comment' post.pk %}" method="POST"> {% csrf_token %}
  {{ form.text.errors }}
   <label for="{{ form.text.id_for_label }}">comment:</label>
   {{ form.text }}
   <button id="comment" type="submit">comment</button>
</form>

Also provide post.pk in {% url 'comment' post.pk %}.

Related