0

I'm trying to create a very simple web app (I'm very new in Django). This app contains (in index.html) a form which has to be dedicated to uploading a block of a text. When user clicks on submit, it returns new page called processed_text with this text.

The problem is that it works when I use GET but when I change GET to POST (in html and django) it returns some exception

Forbidden (403) CSRF verification failed. Request aborted.

And it does not even print 'process_text method' which is in the view.

Here are my codes:

views.py:

def index(request):
    return render(request,'uploading/index.html')

def process_text(request):
    print 'process_text method'
    if 'text_to_translate_name' in request.POST:
        message = 'OK {}'.format(request.POST['text_to_translate_name'])
    return HttpResponse(message)

index.html: without head

<body>
    <h1>Index z TEMPLATES H1</h1>
        <form action="/process_text/" method="post">
            <input type="text" name="text_to_translate_name">
            <input type="submit" value="upload">
        </form>
</body>
</html>

urls.py:

urlpatterns = [
    url(r'^$', views.index),
    url(r'^process_text/$',views.process_text),
]

Do you know where is the problem?

Milano
  • 18,048
  • 37
  • 153
  • 353

1 Answers1

3

You need to add {% csrf_token %} in your form. It inserts a csrf token input field to your form, which is used by Django for security purposes.

So your form looks like -

<form action="/process_text/" method="post">
    {% csrf_token %}
    <input type="text" name="text_to_translate_name">
    <input type="submit" value="upload">
</form>
utkbansal
  • 2,787
  • 2
  • 26
  • 47