简体   繁体   中英

POST http://127.0.0.1:8000/notifications/ajax/ 403 (FORBIDDEN)//using ajax+django

why am I getting this error, I think I have correct ajax functions, I set my urls right...please, any help will be highly appreciated.

<div id='notificationsLoader'>
</div>
<script>
$(document).ready(function(){
  $(".notification-toggle").click(function(e){
    e.preventDefault();
    $.ajax({
      type:"POST",
      url:"{% url 'get_notifications_ajax' %}",
      data: {
        csrfmiddlewaretoken: "{{csrf_token}}",
      },
      success: function(data){
        $("#notificationsLoader").html('<h3>notifications</h3>');
        $(data.notifications).each(function(){
          $("notificationsLoader").append(this + "<br/>")
        })
        console.log(data.notifications);
      },
      error: function(rs, e){
        console.log(rs);
        console.log(e);
      }


    })
  })
})
</script>

In views.py

@login_required
def get_notifications_ajax(request):
    notification = Notification.objects.get(id=id)
    notes =[]

    for note in notifications:
        notes.append(str(note))
    data={
        "notifications":notes
        }
    json_data = json.dumps(data)
    return HttpResponse(json_data, content_type='application/json')

and in urls.py

urlpatterns += patterns('notifications.views',
    url(r'^notifications/$', 'all', name='notifications_all'),
    url(r'^notifications/ajax/$', 'get_notifications_ajax', name='get_notifications_ajax'),
    url(r'^notifications/(?P<id>\d+)/$', 'read', name='notifications_read'),

)

I've tried changing allowing host in my settings.py but it won't work. I'm almost sure the code is correct because I'm following a tutorial and with this code instructor does it without a problem. Thank you,

Full Error

POST http://127.0.0.1:8000/notifications/ajax/ 403 (FORBIDDEN)> ERROR)send @ jquery.min.js:4m.extend.ajax @ jquery.min.js:4(anonymous function) @ (index):359m.event.dispatch @ jquery.min.js:3r.handle @ jquery.min.js:3

Your data is using a csrf_token context variable that I'm guessing you havent set up, more likely you wanted to use the django template tag for the token

  url:"{% url 'get_notifications_ajax' %}",
  data: {
    csrfmiddlewaretoken: "{% csrf_token %}",
  },

Other than that, a 500 error is a server error, when debugging and developing you should be doing so with the DEBUG setting set to true to get more informative errors.

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