[PYTHON] Try Ajax on the Django page

When I try to POST with Javascript, Django's CSRF measures may get caught and fail, but the official document properly describes the measures. http://docs.djangoproject.jp/en/latest/ref/contrib/csrf.html?highlight=csrf#ajax

In addition, I uploaded a copy and paste to Github so that I can reuse it, so if you want to use it, please. https://github.com/juniskw/django_tools/blob/master/csrf_token_ajax.js

Example: An app that alerts you by adding "!!!" to the POSTed characters.

surprise.html

<head>
    <script type="text/javascript" src="{{STATIC_URL}}js/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="https://raw.githubusercontent.com/juniskw/django_tools/master/csrf_token_ajax.js"></script>
</head>
<body>
	<h1>Let's Surprise!</h1>
	<form id="surprise_fm" action="surprise/" method="post">
		<input id="your_txt" type="text" name="your_txt">
		<input id="surprise_btn" type="submit">
	</form>
</body>
<script>
$(document).ready(function() {
	$('#surprise_fm').submit(function() {  //AJAX with the click of a button
		$.ajax({
			'url':$('form#surprise_fm').attr('action'),
			'type':'POST',
			'data':{
				'your_txt':$('#your_txt').val(),
			},
			'dataType':'json',
			'success':function(response){  //It is a process that works when communication is successful, and the returned response is included in the argument.
				alert(response.your_surprise_txt);  //Extract data from response and alert
			},
		});
		return false;
	});
});
</script>

urls.py

#...
url(r'^surprise/', 'views.for_ajax'),
#...

views.py

def for_view(req):    #Function to display the view
	return render(req,'surprise.html')

def for_ajax(req):    #Functions that answer AJAX
	import json
	from django.http import HttpResponse,Http404

	if req.method == 'POST':
		txt = req.POST['your_txt']  #Get POST data
		surprise_txt = txt + "!!!"  #processing

		response = json.dumps({'your_surprise_txt':surprise_txt,})  #Convert to JSON format ...

		return HttpResponse(response,mimetype="text/javascript")  #return. Is JSON treated as javascript?
	
    else:
		raise Http404  #GET request is treated as 404, but in reality it may not be necessary

If you rewrite a part of js as follows, you can just put ** csrf_token ** in the form.

$.ajax({
    // ...
    'data':$('form#surprise_fm').serialize(),
    // ...
});

** serialize ** is probably a method that puts all the input elements in the form together in the form ** {name: value, ...} **. Django's ** csrf_token ** looks like a ** hidden type input element ** if you reveal the seeds, so this method could work like normal form processing.

Recommended Posts

Try Ajax on the Django page
Publish DJango page on heroku: Practice
Deploy the Django app on Heroku [Part 2]
React → Ajax → Django on Linux implementation memo
Deploy the Django app on Heroku [Part 1]
Try hitting the Spotify API in Django.
Python: Try using the UI on Pythonista 3 on iPad
Try CIing the pushed python code on GitHub.
Customize the model page on Django's admin screen
Try using the temperature sensor (LM75B) on the Raspberry Pi.
Try to estimate the number of likes on Twitter
Try Debian + Python 3.4 + django1.7 ...
Try running a Django application on an nginx unit
Make the model a string on a Django HTML template
Django page released on heroku: Preparation my addictive point
Try using Django templates.html
Hello World on Django
[Django] Rename the project
Try FEniCS on Windows!
Try Poerty on Windows
Miscellaneous notes about deploying the django app on Heroku
Try NeosVR on Linux
[Django] How to redirect unlogged-in users to the login page
Install django on python + anaconda and start the server
Try deepdream on Mac
Try using the Python web framework Django (2) --Look at setting.py
Until the start of the django tutorial with pycharm on Windows
I can't log in to the admin page with Django3
Django --Overview the tutorial app on Qiita and add features (2)
Try StyleGAN on Google Colaboratory
Try using the Twitter API
Try using OpenCV on Windows
[Django] Notes on using django-debug-toolbar
Install the JDK on Linux
Try the Taxii server (1. Server settings)
Try "100 knocks on data science" ①
Try using the Twitter API
Django environment development on Windows 10
Install Django on your Mac
Try using the PeeringDB 2.0 API
Watch the video on Fedora31
Paste the link on linux
Hello World (beginners) on Django
Try doubling the PyODE slider
Get started with the Python framework Django on Mac OS X
Quickly install OpenCV 2.4 (+ python) on OS X and try the sample
Django: Fluctuate the number of child forms depending on the number of input items
[Django] Correct the plural form of the model name on the management screen
Disguise the grass on GitHub and try to become an engineer.
[Django] Display registration data associated with users on the registration / edit form (Form)
The story of failing to update "calendar.day_abbr" on the admin screen of django