Created
April 6, 2018 16:10
-
-
Save dvcolgan/9e8d907957b965fae5777cbb42b772e4 to your computer and use it in GitHub Desktop.
Simple PJAX in Django without fancy libraries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form novalidate action="{% url 'thing_create' %}" method="POST" id="thing-form"> | |
{% csrf_token %} | |
{{ form }} | |
<input type="submit" value="Submit" /> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
<h1>Create a Thing</h1> | |
{% include '_thing_create_form.html' %} | |
<script> | |
var $form = $('#thing-form'); | |
var form = $form.get(0); | |
$form.submit(function() { | |
$.ajax({ | |
type: form.method, | |
url: form.action, | |
data: $form.serialize(), | |
success: function(data, textStatus, xhr) { | |
var url = xhr.getResponseHeader('REDIRECT_LOCATION'); | |
if (url) { | |
window.location.replace(url) | |
} else { | |
$form.replaceWith(data); | |
} | |
}, | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def thing_create(request): | |
if request.method == "POST": | |
form = MyForm(request.POST) | |
if form.is_valid(): | |
form.save() | |
# Redirect via Javascript by checking this header | |
response = HttpResponse() | |
response['REDIRECT_LOCATION'] = reverse('nextpage') | |
return response | |
else: | |
form = MyForm() | |
if request.is_ajax(): | |
template_name = '_thing_create_form.html' | |
else: | |
template_name = 'thing_create.html' | |
return render(request, template_name, locals()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment