Skip to content

Instantly share code, notes, and snippets.

@enkore
Created April 21, 2012 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enkore/2437533 to your computer and use it in GitHub Desktop.
Save enkore/2437533 to your computer and use it in GitHub Desktop.
Generic AJAX forms in Django
class BasicDialogForm(object):
dialog = {
"title": _("NOT SET"),
"text": "",
"submit": {
"text": _("Save changes"),
"active": _("Saving..."),
"color": "btn-primary",
},
"id": "some-value",
"form_id": "some-other-value",
}
def prerender(self):
pass
def render(self):
self.prerender()
return render_to_string("forms/dialog.html", {
"dialog": self.dialog,
"form": self,
})
def render_errors(self):
errors = dict()
for field in self:
if field._errors():
errors[field.html_name] = field._errors()
return json.dumps(errors)
class DialogForm(BasicDialogForm, forms.Form):
pass
class ModelDialogForm(BasicDialogForm, forms.ModelForm):
pass
<div class="modal fade" id="dialog-{{ dialog.id }}">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>{{ dialog.title }}</h3>
</div>
<div class="modal-body">
<div class="text">{{ dialog.text|linebreaks}}</div>
<form class="form-horizontal" id="{{ dialog.form_id }}">
<fieldset>
{% for field in form.hidden_fields %}
{{ field }}
{% endfor %}
{% for field in form.visible_fields %}
<div class="control-group">
<label class="control-label" for="{{ field.html_name }}">{{ field.label }}</label>
<div class="controls">
{{ field }}
<p class="help-block">{{ field.help_text }}</p>
</div>
</div>
{% endfor %}
</fieldset>
</form>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn closebtn">Close</a>
<a href="#" class="btn {{ dialog.submit.color }} submitbtn">{{ dialog.submit.text }}</a>
</div>
<script type="text/javascript">
x = function () {
dialog = $( "#dialog-{{ dialog.id }}" );
form = dialog.find( ".form-horizontal" );
btn = dialog.find( ".submitbtn" );
btn.click( function(e) {
$( this ).addClass( "disabled" );
$( this ).text( "Saving..." );
$.ajax( {
type: "POST",
url: dialog.data( "formtarget" ),
data: form.serializeArray(),
success: function(text, status, xhr) {
if( text === true ) {
dialog.modal( "hide" );
location.reload();
} else {
btn.text( "{{ dialog.submit.text }}" );
btn.removeClass( "disabled" );
form.find( ".control-group" ).removeClass
$.each( text, function(i, ex) {
e = $( "#id_" + i ).parents( ".control-group" ).first();
e.addClass( "error" )
e.find( ".controls" ).append( "<span class='help-inline'></span>" );
e.find( ".help-inline" ).text( String( ex ) );
} );
}
},
error: function(xhr, text, et) {
alert(text + xhr.responseText);
},
dataType: "json"
} );
} );
}
setTimeout(x, 150);
</script>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment