Last active
March 15, 2024 22:00
-
-
Save adamghill/8634935 to your computer and use it in GitHub Desktop.
Django AJAX forms. Uses a bunch of requirements installed in https://github.com/adamghill/django-template.
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
(function() { | |
$('a.button').click(function(e) { | |
var $form = $("#form"); | |
$('#error').hide(); | |
$('input').removeClass('error'); | |
var handleError = function() { | |
$('#error').show(); | |
} | |
var postData = $form.serialize(); | |
$.post("/", postData, function(data) { | |
if (data.errors) { | |
$('#error').show(); | |
for (error in data.errors) { | |
$('input[name="' + error + '"]').addClass('error'); | |
console.log('Error on field with name: ', error); | |
} | |
handleError(); | |
} else { | |
// console.log('success', data); | |
} | |
}).error(function() { | |
handleError(); | |
}); | |
}); | |
})(); |
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
from django.shortcuts import render_to_response | |
from django.template import RequestContext | |
from django.views.decorators.csrf import csrf_protect | |
from .forms import ModelForm | |
from .models import Model | |
from django_utils.http_response import JsonHttpResponse | |
from first import first | |
import simplejson as json | |
import uuid | |
@csrf_protect | |
def index(request): | |
form = None | |
if request.method == 'POST': | |
model_uuid = request.POST.get('uuid') | |
model = first(model.objects.filter(uuid=model_uuid)) | |
if not model: | |
model = Model(uuid=model_uuid) | |
form = ModelForm(request.POST, instance=model) | |
if form.is_valid(): | |
model = form.save() | |
data = json.dumps({ | |
'uuid': str(model.uuid) | |
}) | |
else: | |
# Since form.errors is a proxy need to create a dict from it with unicode | |
data = json.dumps({'errors': dict([(k, [unicode(e) for e in v]) for k,v in form.errors.items()])}) | |
if request.is_ajax(): | |
return JsonHttpResponse(data) | |
else: | |
form = ModelForm() | |
model_uuid = str(uuid.uuid4()).replace('-', '') | |
return render_to_response('www/index.html', { | |
'form': form, | |
'model_uuid': str(model_uuid), | |
}, context_instance=RequestContext(request) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment