souza
souza

Reputation: 1438

"Forbidden 403 - CSRF verification failed" when using .submit(function) in Django form

I've been developing in application with Django that has a bunch of forms, each one in a different page. In one of the first views, I just ask the user a simple information, that is POST sent to Python and used to some formulas. The code I used to do so is show below, and it runs smoothly:

<html>
<head>
    <title>Data</title>
</head>

{% load staticfiles %}
<link rel="stylesheet" href="{% static 'app/content/bootstrap.css' %}">
<link rel="stylesheet" href="{% static 'app/content/custom.css' %}">

<script src="{% static 'app/scripts/jquery-1.10.2.min.js' %}"></script>
<script src="{% static 'app/scripts/jquery.validate.js' %}"></script>
<script src="{% static 'app/scripts/jquery.maskedinput.min.js' %}"></script>
<script src="{% static 'app/scripts/custom.js' %}"></script>

{% if error == 404 %}
<label>Who are you? Go away!</label>
<br>
{% endif %}
Welcome! Give me your data!
<body>
    <form action="/search/" method="post" id="myPrettyForm">
        {% csrf_token %}
        <input type="text" name="q" id="q">
        <input type="submit" value="Go!">
    </form>
</body>
<script type="text/javascript">

    $("#q").mask("00000000000");

</script>
</html>

As I said, this code runs nicely. However, I want to add a function, in which, once I click the "submit", the q input field is disabled. To do so, I tried adding this piece of code to the script above:

$("#myPrettyForm").submit(function () {
    $("#myPrettyForm:input").prop("disabled", true);
});

However, when I add this snippet to my code, everytime I try to submit my form, I receive a "Forbidden (403) CSRF verification failed. Request aborted." error. According to this, this error is commonly related to the form not having the {% csrf_token %} element. However, my form already has this element.

So what am I doing wrong in here? And if I'm using the wrong method to prevent my user to write in the inputs after the form is submitted, which other method could I use?

Upvotes: 0

Views: 387

Answers (1)

Yugandhar Chaudhari
Yugandhar Chaudhari

Reputation: 3974

request.POST is a dictionary with form data. Disabling input class will make all input including csrf_token as disabled. Right way is to reference the component by id and keeping the component as "readonly" like you did $("#fieldId").prop("readonly", true);

Upvotes: 1

Related Questions