1

I'm getting this common error as in the title. I'm doing a project in Django in a virtual environment folder.

setting.py:

        MIDDLEWARE = [
            'django.middleware.security.SecurityMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.middleware.common.CommonMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
            'django.middleware.clickjacking.XFrameOptionsMiddleware',
        ]

index.html:

        {% load static %}
        <!DOCTYPE html>
        <html>

        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Instapic</title>
            <link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}">
            <link rel="stylesheet" href="{% static 'assets/css/Login-Form-Clean.css' %}">
            <link rel="stylesheet" href="{% static 'assets/css/styles.css' %}">
        </head>

        <body>
            <div class="login-clean">
                <form method="post">
                    {% csrf_token %}

                    <h2 class="sr-only">Login Form</h2>
                    <div class="illustration">
                            <div style="display: none" id="errors" class="well form-error-message"></div>
                            <img src="{% static 'assets/img/logo.jpg' %}">
                    </div>
                    <div class="form-group">
                        <input class="form-control" id="username" type="text" name="username" required="" placeholder="Username" maxlength="20" minlength="4">
                    </div>
                    <div class="form-group">
                        <input class="form-control" id="email" type="email" name="email" required="" placeholder="Email" maxlength="100" minlength="6">
                    </div>
                    <div class="form-group">
                        <input class="form-control" id="password" type="password" name="password" required="" placeholder="Password" maxlength="20" minlength="6">
                    </div>
                    <div class="form-group">
                        <button class="btn btn-primary btn-block" id="go" type="submit">Create Account</button>
                    </div><a href="#" class="forgot">Already got an account? Login here ...</a></form>
            </div>
            <script src="{% static 'assets/js/jquery.min.js' %}"></script>
            <script src="{% static 'assets/bootstrap/js/bootstrap.min.js' %}"></script>
            <script src={% static "assets/js/django-ajax.js" %}></script>
            <script type="text/javascript">
                $(document).ready(function() {
                $('#go').click(function() {
                $.post("ajax-sign-up",
            {
                username: $("#username").val(),
                email: $("#email").val(),
                password: $("#password").val()
            },
            function(data, status){
            if (JSON.parse(data).Status == 'Success') {
                window.location = '/';
            } else {
                $('#errors').html("<span>" + JSON.parse(data).Message + "</span>")
                $('#errors').css('display', 'block')
            }
            });
                return false;
                })
        })
            </script>
        </body>

        </html>

I added {% csrf_token %} in my html file trying fix this - didn't work. I've found online this tag example:

<input type="hidden" id="csrf_token" value='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>.

Unfortunately I don't know how to use it in order to fix my error. Thanks for help

3
  • 1
    This happens when? when clicking on #go button? Did you read this Commented Aug 29, 2019 at 13:43
  • 1
    It would probably be easier if instead of passing the fields individually in your ajax post request you just get the form data (which would include the csrftoken). Or you follow the instructions in the link I gave in my previous comment. Commented Aug 29, 2019 at 13:44
  • i did not get it Commented Aug 29, 2019 at 13:51

2 Answers 2

3

I guess, instead of post a form you are posting values. You need to add csrfmiddlewaretoken key while execute $.post() statement.

This is not Tested but it may be fix your problem

  csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value

or

 csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val()

add this line in HTML file by updating

$.post("ajax-sign-up",
    {
        username: $("#username").val(),
        email: $("#email").val(),
        password: $("#password"),
        csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val()
    },

updated code is :

    {% load static %}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Instapic</title>
    <link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'assets/css/Login-Form-Clean.css' %}">
    <link rel="stylesheet" href="{% static 'assets/css/styles.css' %}">
</head>

<body>
    <div class="login-clean">
        <form method="post">
            {% csrf_token %}

            <h2 class="sr-only">Login Form</h2>
            <div class="illustration">
                    <div style="display: none" id="errors" class="well form-error-message"></div>
                    <img src="{% static 'assets/img/logo.jpg' %}">
            </div>
            <div class="form-group">
                <input class="form-control" id="username" type="text" name="username" required="" placeholder="Username" maxlength="20" minlength="4">
            </div>
            <div class="form-group">
                <input class="form-control" id="email" type="email" name="email" required="" placeholder="Email" maxlength="100" minlength="6">
            </div>
            <div class="form-group">
                <input class="form-control" id="password" type="password" name="password" required="" placeholder="Password" maxlength="20" minlength="6">
            </div>
            <div class="form-group">
                <button class="btn btn-primary btn-block" id="go" type="submit">Create Account</button>
            </div><a href="#" class="forgot">Already got an account? Login here ...</a></form>
    </div>
    <script src="{% static 'assets/js/jquery.min.js' %}"></script>
    <script src="{% static 'assets/bootstrap/js/bootstrap.min.js' %}"></script>
    <script src={% static "assets/js/django-ajax.js" %}></script>
    <script type="text/javascript">
        $(document).ready(function() {
        $('#go').click(function() {
        $.post("ajax-sign-up",
    {
        username: $("#username").val(),
        email: $("#email").val(),
        password: $("#password").val(),
        csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val()
    },
    function(data, status){
    if (JSON.parse(data).Status == 'Success') {
        window.location = '/';
    } else {
        $('#errors').html("<span>" + JSON.parse(data).Message + "</span>")
        $('#errors').css('display', 'block')
    }
    });
        return false;
        })
})
    </script>
</body>

</html>
Sign up to request clarification or add additional context in comments.

3 Comments

where should i add this? settings.py?
No in your HTML file. I update the code you can check it.
Try with @dirkgroten solution, its better solution in this case.
1

If you're just posting the contents of a HTML form with id signup-form (add that to the <form>), and your form has the {% csrf_token %}, then you can do that in ajax using:

$.post("ajax-sign-up", $("#signup-form").serialize(), function(data, status){...})

2 Comments

Look at your own HTML template, you already wrote $.post("ajax-sign-up")... yourself! I'm only suggesting to submit all the form fields instead of the 3 you wrote explicitly.
see the answer of @somil below, where it's spelled out for you. But please take your time and read the link until you understand it completely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.