Skip to content

Instantly share code, notes, and snippets.

@dvcolgan
Created April 6, 2018 16:10
Show Gist options
  • Save dvcolgan/9e8d907957b965fae5777cbb42b772e4 to your computer and use it in GitHub Desktop.
Save dvcolgan/9e8d907957b965fae5777cbb42b772e4 to your computer and use it in GitHub Desktop.
Simple PJAX in Django without fancy libraries
<form novalidate action="{% url 'thing_create' %}" method="POST" id="thing-form">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
<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>
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