GG WordPress
GG WordPress

Reputation: 63

request.POST.get() showing a None when print is used

Like the question said, when I print, it shows the list/string first then a "None" in the end just like this:

["a","b","c"]
"test"
None
None

script

$(document).ready(function() {
            $("#export").click(function () {
              var test = "test";
              var array1 = ['a','b','c'];
              $.ajax({
                url: '/export/csv',
                data: {'array1': JSON.stringify(array1), 'test': JSON.stringify(test)},
                dataType: 'json',
                type: 'POST',
                success: function (data) {
                }
              });
            });
        });

views.py

@csrf_exempt
def export_csv(request):

    print(request.method)
    test1 = request.POST.get('test')
    array1 = request.POST.get('array1')

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="product-inventory.csv"'

    print(array1)
    print(test1)

    writer = csv.writer(response)
    writer.writerow(['Test1')

    for t in array1:
        writer.writerow([t])

    return response

urls.py

url(r'^export/csv$', product_views.export_csv, name='export_csv')

I know I'm missing something in my views.py. If you could point me to the right direction, that would be great.

Thanks in advance!

Upvotes: 0

Views: 1388

Answers (1)

AKS
AKS

Reputation: 19831

Copied from my comments:

It could be that when the values are printed that's POST request while None values are getting printed in GET request of the same URL.

Looking at the output of print(request.method) it is confirmed that the URL is being accessed two times. One with POST method and other time with GET method.

None values are printed during the GET method request because at that time request.POST doesn't contain the keys you are looking for.

If you only want to serve POST methods, you could restrict the allowed HTTP methods

from django.views.decorators.http import require_http_methods

@csrf_exempt
@require_http_methods(["POST"])
def export_csv(request):
    .... # your implementation

But, you should also try to find out the origin of the GET method first.

Upvotes: 2

Related Questions