简体   繁体   中英

How to retrieve post data from view of django app

All I am new to jquery and Django. I used the following code to post when the button with id 'submit_data' is clicked. Is it possible to retrieve the dictionary { data_key: 'myString'} from the views.py of the Django app? If yes how?

$(function() {

    $('#submit_data').on('click',function() {
        $.post('/url/', { data_key: 'myString'}, function(result) {
            alert('successfully posted');
        });
    });
});

request.data is used to fetch data from your frontend

it is a dictionary-like object that lets you access submitted data by key name.

Try this: request.data.get('data_key',None). To avoid KeyError, you can use.get() which provides value if key found else None is returned.

For a POST request with form data, you can use request.POST :

def my_view(request):
    print(request.POST)
    # ...

For a POST request with JSON data, you need to decode request.body :

import json

def my_view(request):
    # TODO: missing a suitable `content-type` header check
    data = json.loads(request.body.decode())
    print(data)
    # ...

In template script

$(function() {

    $('#submit_data').on('click',function() {
        $.post('/url/', { 'data_key': 'myString'}, function(result) {
            alert('successfully posted');
        });
    });
});

in views.py

if request.method == 'POST':
    data = request.POST.get('data_key', None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM