intelis
intelis

Reputation: 8068

Simple django POST not working

I have a form like this:

<form action="{% url "forum.posts" forum=forum.slug thread=thread.slug %}" method="POST">
    {% csrf_token %}
    <div class="form-group">
        <textarea class="form-control" placeholder="Začni tipkati.."></textarea>
    </div>
    <input type="submit" class="btn btn-success" value="Pošlji odgovor">
</form>

views.py

'''
Display all posts in a thread or create a new post in a thread.
'''
def posts(request, forum, thread):
    forum = Forum.objects.get(slug=forum)

    thread = Thread.objects.get(slug=thread)

    if request.method == "POST":

        return HttpResponse('ok')

    posts = thread.posts.all()

    return render(request, 'forum/posts.html', {
        'forum': forum,
        'thread': thread,
        'posts': posts
    })

urls.py (relevant part):

# List all posts in a thread / Submit a post to a forum
url(r'^(?P<forum>[-\w]+)/(?P<thread>[-\w]+)/$', 'forum.views.posts', name='forum.posts'),

HTML output:

<form action="/forum/o-spletiscu/novatemaa/" method="post">
    <input type="hidden" name="csrfmiddlewaretoken" value="4PQWDsAfHyjrhUnYU5P9vVhtaY3vLPBU">
    <div class="form-group">
        <textarea name="post-body" class="form-control" placeholder="Začni tipkati.."></textarea>
    </div>
    <input type="submit" class="btn btn-success" value="Pošlji odgovor">
</form>

After I hit submit, I expect ok to be returned, instead page refreshes and nothing happens. Normal GET requests are working though..

What am I missing?

Edit: It's working when I use @csrf_exempt on posts method.

Upvotes: 1

Views: 4027

Answers (1)

Othman
Othman

Reputation: 3018

page refreshes and nothing happens

Problem with your action value. try to inspect it and find wither the url is correct or not.

OR

your form does not have any input with name property.

Try this:

  <form action="{% url "forum.posts" forum=forum.slug thread=thread.slug %}" method="POST">
      {% csrf_token %}
      <div class="form-group">
          <textarea class="form-control" placeholder="Začni tipkati.." name="something"></textarea>
      </div>
      <input type="submit" class="btn btn-success" value="Pošlji odgovor">
  </form>

Upvotes: 1

Related Questions