Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
3 views
in Web Technology by (19.9k points)

I'm Trying to pass data from javascript on a page to another view in my django project.But it seems the view isn't getting called. What I want to do is that Using JS I want to just get data from page containing the JS and print it from django view to console.

js on html page:

    <script>

    var URL="{% url 'projects:Unread' %}"

    function Unread(){

            var data = {'count': '5', 'X-csrfmiddlewaretoken': csrfmiddlewaretoken};

            $.post(URL, data);

        }

       </script>

somewhere from page I'm calling this function,I have used an alert to make sure it is called.

my urls.py :

    path('notification/',Unread,name='Unread')

my view:

def Unread(request):

  count=request.body['count']

  print("hello")

  print("count status ",count)

I have also tried request.POST to get value but now working.What I exactly want is to get 'count' from JS to my view.But its not happening, Even the 'hello' is not getting printed it's not even related to JS.I'm fairly new to both django and JS so I'm not sure what I'm doing wrong.

2 Answers

0 votes
by (25.1k points)

As the commenters mentioned, you should double check to make sure your POST isn't failing for CSRF reasons. If you're certain it is not, you can access form-encoded post variables using request.POST, don't use request.body.

def Unread(request):

    count=request.POST['count']

    print("hello")

    print("count status ",count)

0 votes
by (1.8k points)

As others have pointed out, it’s crucial to check if your POST request is failing due to CSRF issues. If you're sure that's not the case, you should use request.POST to access form-encoded variables instead of request.body.

In your view, you can set it up like this:

First, make sure you handle POST requests properly.To get the count value from the incoming data, you should use request.POST['count'].To set up your view, check if the request method is POST. If it is, retrieve the count value like this:

def Unread(request):
if request.method == "POST":
message_count = request.POST['count']
print("View accessed")
print("Count value:", message_count)
return JsonResponse({'status': 'success'})
return JsonResponse({'status': 'error'}, status=400)



Make sure your CSRF token is sent correctly from your JavaScript code. Using request.POST will help you handle the data coming from your JavaScript function effectively.

Related questions

0 votes
1 answer

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...