Hago una solicitud POST a través de AJAX sin formulario HTML. ¿Hay algún problema de seguridad? ¿Por qué no hay error csrf? ¿Porque no envío ningún dato csrf y csrf está habilitado en django?
alternar-estado.js
jQuery(document).ready(function($) { $("#switch-status").click(function(){ $.ajax({ url: '/account/switches/', data: {'toggle': 'status'} }); }); });ver.py
@login_required def switches(request): toggle = request.GET.get('toggle', None) current_user = request.user update = Switches.objects.get(owner=current_user) if toggle == 'status': if update.status is True: update.status = False else: update.status = True update.save() return HttpResponse('')El método predeterminado de la función ajax es GET , no POST . Entonces, haciendo un:
$.ajax({ url: '/account/switches/', data: {'toggle': 'status'} }); implica que se realiza un GET ajax. Entonces, no estás haciendo una solicitud POST .
Si desea una solicitud POST , hágalo así:
$.ajax({ method: 'POST', url: '/account/switches/', data: {'toggle': 'status'} }); Por supuesto, debe incluir el token CSRF, ya que fallará si intenta POST sin incluir uno. Mira aquí cómo lograr eso.