Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a Django view for a POST request

I have written a very small example: a junit button which sends a POST request with a pair of values:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Button - Default functionality</title>
    <script src="{{STATIC_URL}}js/jquery-1.9.1.js"></script>
    <script src="{{STATIC_URL}}js/jquery-ui-1.10.3.custom.js"></script>
    <link rel="stylesheet" href="{{STATIC_URL}}css/jquery-ui-1.10.3.custom.css">

  <script>
  $(function() {
    $( "button" )
      .button()
      .click(function( event ) {
        var postdata = {
            'value1': 7,
            'value2': 5
        };
        $.post('', postdata); // POST request to the same view I am now
        window.alert("Hello world!"); // To know it is working
      });
  });
  </script>
</head>
<body>

<button>Submit</button>


</body>
</html>

So, the view is rendered when a GET request is sent to localhost:8000/button/, and when the button is pushed a POST request is also sent to localhost:8000/button/.

urls.py

from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^button/$', 'helloworld.views.buttonExample'),
    )

views.py

def buttonExample(request):
    print 'RECEIVED REQUEST: ' + request.method
    if request.method == 'POST':
        print 'Hello'
    else: #GET
        return render(request, 'buttonExample.html')

When the GET request is done, the view is displayed correctly and I can also read at Django console the lines:

RECEIVED REQUEST: GET <---- This line is because of my print
[28/May/2013 05:20:30] "GET /button/ HTTP/1.1" 200 140898
[28/May/2013 05:20:30] "GET /static/js/jquery-1.9.1.js HTTP/1.1" 304 0
[28/May/2013 05:20:30] "GET /static/js/jquery-ui-1.10.3.custom.js HTTP/1.1" 304 0
[28/May/2013 05:20:30] "GET /static/css/jquery-ui-1.10.3.custom.css HTTP/1.1" 304 0
...

And when the button is pushed, I can see:

[28/May/2013 05:20:34] "POST /register/ HTTP/1.1" 403 142238

But "RECEIVED REQUEST: POST" is never printed. Neither is "Hello". It seems like the urls.py is not serving the view when a POST arrived, because in Firebug I can see that POST status is 403 FORBIDDEN.

This is probably a silly newbie mistake, but I don't know what am I missing. I have read the django book chapter about advanced URLConf and Views, and it looks like it should work just by checking request.method value.

like image 996
Roman Rdgz Avatar asked May 28 '13 10:05

Roman Rdgz


People also ask

How do I see POST requests in Django?

When a POST request is received at the Django server, the data in the request can be retrieved using the HTTPRequest. POST dictionary. All the data of the POST request body is stored in this dictionary. For example, you can use the following code snippet inside your view.py file.

How do you receive data from a Django form with a post request?

Using Form in a View In Django, the request object passed as parameter to your view has an attribute called "method" where the type of the request is set, and all data passed via POST can be accessed via the request. POST dictionary. The view will display the result of the login form posted through the loggedin.

What is request method == POST in Django?

method == "POST" is a boolean value - True if the current request from a user was performed using the HTTP "POST" method, of False otherwise (usually that means HTTP "GET", but there are also other methods).


2 Answers

This is by design. Your POST data must contain csrfmiddlewaretoken value. You can get it from your cookies and then send it with POST requests. Details here. For your specific case, you can do this -

<script>
$(function () {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    $("button")
        .button()
        .click(function (event) {
            var postdata = {
                'value1': 7,
                'value2': 5,
                'csrfmiddlewaretoken': csrftoken
            };
            $.post('', postdata); // POST request to the same view I am now
            window.alert("Hello world!"); // To know it is working
        });
});
</script>
like image 121
Bibhas Debnath Avatar answered Sep 19 '22 01:09

Bibhas Debnath


You are receiving a 403 because of CSRF protection - you have not provided a token to protect yourself from attacks. The documentation tells you all you need to know.

like image 20
Daniel Roseman Avatar answered Sep 18 '22 01:09

Daniel Roseman